枚举时如何更改Dictionary的值?以下代码不起作用,因为枚举时我们无法更改字典的值.有没有办法绕过它?或者没有办法?谢谢
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];
}
}
Run Code Online (Sandbox Code Playgroud)
最简单的方法是先复制一份.由于您只需要键值对,您可以将它们放在列表中,而不是构建新的字典.此外,您可以避免使用相当多的查找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;
}
}
Run Code Online (Sandbox Code Playgroud)
在枚举之前复制需要枚举的值,然后可以更改原始源.
由于您实际上并未使用该值,因此可以将代码更改为:
foreach (string key in mydictionary.Keys.ToArray())
if (otherdictionary.ContainsKey(key))
mydictionary[key] = otherdictionary[key];
else
otherdictionary[key] = mydictionary[key];
Run Code Online (Sandbox Code Playgroud)
注意使用.ToArray()那里来制作密钥集合的临时数组副本.现在它与源字典分开,因此您可以根据需要更改字典.