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.
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.
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
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);
}
在回答“我无法在 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);
}
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>
.
我刚刚回答了列表的相同(更新)问题,所以字典也是一样的。
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);
}
请注意,我们必须在循环之外进行更新,因此我们在枚举字典时不会修改它。这也检测到由于使两个键相同而引起的冲突 - 它会抛出(由于使用Add
)。
示例 - 使所有键小写并修剪所有值,使用Dictionary<string, string>
:
myDict.MutateEach(key => key.ToLower(), value => value.Trim());
如果键在小写时不是唯一的,则会抛出。