user2533162
user2533162

Reputation:

Updating a dictionary dynamically with foreach

When trying to update a Dictionary with the following:

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

And exception is thrown. Is there any way to dynamically update the dictionary WITHOUT making any kind of key or value backups?

EDIT!!!!!! View code. I realized that this portion was actually doable. The real case is this. I thought they would be the same, but they are not.

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

Upvotes: 4

Views: 987

Answers (2)

keyboardP
keyboardP

Reputation: 69372

You can either loop over the dictionary (you need to use ToList because you can't change a collection that is being looped over in a foreach loop)

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

or you can do it in one line of LINQ as you're setting the same value to all the keys.

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

Updated question

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

and the 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 modify the collection directly.

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

Upvotes: 2

Mike Dinescu
Mike Dinescu

Reputation: 55720

Any reason why you're not iterating over the keys?

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

Upvotes: 4

Related Questions