如何枚举字典?
假设我使用foreach()
进行字典枚举。然而,在foreach()
中无法更新键值对。因此,我需要其他方法。
如何枚举字典?
假设我使用foreach()
进行字典枚举。然而,在foreach()
中无法更新键值对。因此,我需要其他方法。
Dictionary<int, string> dic;
foreach(string s in dic.Values)
{
Console.WriteLine(s);
}
或者是KeyValuePairs
foreach(KeyValuePair<int, string> kvp in dic)
{
Console.WriteLine("Key : " + kvp.Key.ToString() + ", Value : " + kvp.Value);
}
或者键值foreach(int key in dic.Keys)
{
Console.WriteLine(key.ToString());
}
如果您希望更新字典中的项,需要稍微不同地这样做,因为您无法在枚举实例时更新该实例。您需要枚举另一个不被更新的集合,就像这样: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
}
要删除项目,可以按照类似的方式进行操作,枚举要删除的项目的集合,而不是字典本身。
List<int> keys = new List<int>() { 1, 3 };
foreach(int key in keys)
{
dic.Remove(key);
}
针对问题“I can't update value/key inside 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。有三种方法:您可以枚举 Keys
属性,也可以枚举 Values
属性,或者枚举字典本身,该字典是 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());
如果将键名转换为小写后不唯一,会抛出异常。