C#中的字典枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/676880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dictionary enumeration in C#
提问by Ravi
How do I enumerate a dictionary?
如何枚举字典?
Suppose I use foreach()
for dictionay enumeration. I can't update a key/value pair inside foreach()
. So I want some other method.
假设我foreach()
用于字典枚举。我无法更新里面的键/值对foreach()
。所以我想要一些其他的方法。
回答by Ian
To enumerate a dictionary you either enumerate the values within it:
要枚举字典,您可以枚举其中的值:
Dictionary<int, string> dic;
foreach(string s in dic.Values)
{
Console.WriteLine(s);
}
or the KeyValuePairs
或 KeyValuePairs
foreach(KeyValuePair<int, string> kvp in dic)
{
Console.WriteLine("Key : " + kvp.Key.ToString() + ", Value : " + kvp.Value);
}
or the keys
或钥匙
foreach(int key in dic.Keys)
{
Console.WriteLine(key.ToString());
}
If you wish to update the items within the dictionary you need to do so slightly differently, because you can't update the instance while enumerating. What you'll need to do is enumerate a different collection that isn't being updated, like so:
如果您希望更新字典中的项目,您需要稍微改变一下,因为您无法在枚举时更新实例。您需要做的是枚举一个未更新的不同集合,如下所示:
Dictionary<int, string> newValues = new Dictionary<int, string>() { 1, "Test" };
foreach(KeyValuePair<int, string> kvp in newValues)
{
dic[kvp.Key] = kvp.Value; // will automatically add the item if it's not there
}
To remove items, do so in a similar way, enumerating the collection of items we want to remove rather than the dictionary itself.
要删除项目,以类似的方式执行,枚举我们要删除的项目集合而不是字典本身。
List<int> keys = new List<int>() { 1, 3 };
foreach(int key in keys)
{
dic.Remove(key);
}
回答by Matthias Meid
Foreach. There are three ways: You can enumerate over the Keys
property, over the Values
property or over the dictionary itself which is an enumerator of KeyValuePair<TKey, TValue>
.
Foreach。有三种方法:您可以枚举Keys
属性、Values
属性或字典本身(它是 的枚举器)KeyValuePair<TKey, TValue>
。
回答by spender
In answer to the problem "I can't update value/key inside foreach()", you cannot modify a collection while enumerating it. I would approach this by making a copy of the Keys collection:
为了回答“我无法在 foreach() 中更新值/键”的问题,您无法在枚举集合时修改它。我会通过制作 Keys 集合的副本来解决这个问题:
Dictionary<int,int> dic=new Dictionary<int, int>();
//...fill the dictionary
int[] keys = dic.Keys.ToArray();
foreach (int i in keys)
{
dic.Remove(i);
}
回答by Daniel Earwicker
I just answered the same (updated) question for lists, so here's the same thing for dictionaries.
我刚刚回答了列表的相同(更新)问题,所以字典也是一样的。
public static void MutateEach(this IDictionary<TKey, TValue> dict, Func<TKey, TValue, KeyValuePair<TKey, TValue>> mutator)
{
var removals = new List<TKey>();
var additions = new List<KeyValuePair<TKey, TValue>>();
foreach (var pair in dict)
{
var newPair = mutator(pair.Key, pair.Value);
if ((newPair.Key != pair.Key) || (newPair.Value != pair.Value))
{
removals.Add(pair.Key);
additions.Add(newPair);
}
}
foreach (var removal in removals)
dict.Remove(removal);
foreach (var addition in additions)
dict.Add(addition.Key, addition.Value);
}
Note that we have to do the updates outside the loop, so we aren't modifying the dictionary as we enumerate it. Also this detects clashes caused by making two keys the same - it will throw (due to the use of Add
).
请注意,我们必须在循环外进行更新,因此我们不会在枚举字典时修改它。此外,这会检测由使两个键相同引起的冲突 - 它会抛出(由于使用Add
)。
Example - make all keys lowercase and trim all values, with a Dictionary<string, string>
:
示例 - 使所有键小写并修剪所有值,使用Dictionary<string, string>
:
myDict.MutateEach(key => key.ToLower(), value => value.Trim());
If the keys are not unique when made lowercase, this will throw.
如果键在小写时不唯一,则会抛出。