开发者

how to change Dictionary's value when enumerate it?

开发者 https://www.devze.com 2022-12-27 17:26 出处:网络
how to change Diction开发者_如何转开发ary\'s value when enumerate it? the following code doesn\'t work, because we can not change dictionary\'s value when enumerating it. Is there any way to get arou

how to change Diction开发者_如何转开发ary's value when enumerate it? the following code doesn't work, because we can not change dictionary's value when enumerating it. Is there any way to get around it? Or NO WAY? Thanks

foreach (KeyValuePair<string, int> kvp in mydictionary)
        {
            if (otherdictionary.ContainsKey(kvp.Key))
            {
                mydictionary[kvp.Key] = otherdictionary[kvp.Key];

            }
            else
            {
                otherdictionary[kvp.Key] = mydictionary[kvp.Key];
            }
        }


The simplest way would be to take a copy first. As you only want the key value pairs, you might as well put them in a list rather than building a new dictionary though. Also, you can avoid doing quite as many lookups using TryGetValue.

var copy = myDictionary.ToList();
foreach (KeyValuePair<string, int> kvp in copy)
{
    int otherValue;
    if (otherdictionary.TryGetValue(kvp.Key, out otherValue))
    {
        mydictionary[kvp.Key] = otherValue;
    }
    else
    {
        otherdictionary[kvp.Key] = kvp.Value;
    }
}


Make a copy of the values you need to enumerate over before you enumerate over them, then you can change the original source.

Since you don't actually use the value, you can change the code to this:

foreach (string key in mydictionary.Keys.ToArray())
    if (otherdictionary.ContainsKey(key))
        mydictionary[key] = otherdictionary[key];
    else
        otherdictionary[key] = mydictionary[key];

Note the use of .ToArray() there to make a temporary array copy of the key collection. This is now separate from the source dictionary, so you can change the dictionary all you want.


another option, copy the keys collection to an array and use it in for each loop -

string[] arr1 = new string[mydictionary.Count];

mydictionary.Keys.CopyTo(arr1,0);

    foreach (string j in arr1)
    {
        if (otherdictionary.ContainsKey(j))
        {
            mydictionary[j] = otherdictionary[j];

        }
        else
        {
            otherdictionary[j] = mydictionary[j];
        } 
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消