Dynamic dictionary update with foreach

When trying to update a dictionary with the following:

foreach(KeyValuePair<string, string> pair in dict) { dict[pair.Key] = "Hello"; } 

And an exception is thrown. Is there a way to dynamically update a dictionary WITHOUT creating any backups of keys or values?

EDIT !!!!!! View code. I realized that this part is really doable. The real case is this. I thought they would be the same, but it is not.

 foreach(KeyValuePair<string, string> pair in dict) { dict[pair.Key] = pair.Key + dict[pair.Key]; } 
+4
source share
2 answers

Any reason why you don't iterate over the keys?

 foreach(var key in dict.Keys) { dict[key] = "Hello"; } 
+4
source

You can either ToList over the dictionary (you need to use ToList because you cannot change the collection that loops in the foreach loop)

 foreach(var key in dict.Keys.ToList()) { dict[key] = "Hello"; } 

or you can do this on a single LINQ line, since you are setting the same value for all keys.

 dict = dict.ToDictionary(x => x.Key, x => "Hello"); 

Updated Question

 foreach (var key in dict.Keys.ToList()) { dict[key] = key + dict[key]; } 

and LINQ version

 dict = dict.ToDictionary(x => x.Key, x => x.Key + x.Value); 

If you want to avoid using ToList , you can use ElementAt so that you can directly modify the collection.

 for (int i = 0; i < dict.Count; i++) { var item = dict.ElementAt(i); dict[item.Key] = item.Key + item.Value; } 
+2
source

Source: https://habr.com/ru/post/1488755/


All Articles