Edit: I don't feel this was duplicate- I did fail to elaborate clearly that I wanted to know an efficient way to pad char's to the left of my dictionary values. The question I marked as answer should clarify as it is a very different answer than the answer in other thread. Sorry, I worded it wrong.
I am trying to verify that all the values within my Dictionary are a certain length, and if they are not, pad them with '0' to the left. I know "what" the issue is, I am reading through the dictionary's KVP and then modifying it which of course throws an exception, but I am not sure how to modify my code to make it "legal"
class prefixMe
{
Dictionary<string, string> d = new Dictionary<string, string>();
public prefixMe()
{
d.Add("one", "123456");
d.Add("two", "678");
d.Add("three", "13");
foreach(KeyValuePair<string,string> k in d)
{
StringBuilder sb = new StringBuilder(k.Value);
while(sb.Length != 10)
{
Console.WriteLine("Key:{0}\tValue:{1}", k.Key, sb);
sb.Insert(0, '0');
}
d[k.Key] = sb.ToString();
//k.Value.Replace(k.Value, sb.ToString());// = sb.ToString();
Console.WriteLine("Key:{0}\tNew Value:{1}", k.Key, d[k.Key]);
break;
}
}
}
The break; stops the code from throwing an error, but also makes it so it does not go through for the other values as it breaks out of the foreach loop.
The result should be:
0000123456
0000000678
0000000013