C#中的字典枚举

Rav*_*avi 23 .net c# dictionary enumeration

如何枚举字典?

假设我foreach()用于dictionay枚举.我无法更新里面的键/值对foreach().所以我想要一些其他的方法.

Ian*_*Ian 79

要枚举字典,您要枚举其中的值:

Dictionary<int, string> dic;

foreach(string s in dic.Values)
{
   Console.WriteLine(s);
}
Run Code Online (Sandbox Code Playgroud)

或KeyValuePairs

foreach(KeyValuePair<int, string> kvp in dic)
{
   Console.WriteLine("Key : " + kvp.Key.ToString() + ", Value : " + kvp.Value);
}
Run Code Online (Sandbox Code Playgroud)

或钥匙

foreach(int key in dic.Keys)
{
    Console.WriteLine(key.ToString());
}
Run Code Online (Sandbox Code Playgroud)

如果您希望更新字典中的项目,则需要稍微改变一下,因为在枚举时无法更新实例.您需要做的是枚举一个未更新的不同集合,如下所示:

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
}
Run Code Online (Sandbox Code Playgroud)

要删除项目,请以类似的方式执行此操作,枚举我们要删除的项目集合,而不是字典本身.

List<int> keys = new List<int>() { 1, 3 };
foreach(int key in keys)
{
   dic.Remove(key);
}
Run Code Online (Sandbox Code Playgroud)

  • 我希望枚举键比仅枚举值更常见(至少在我的经验中),因为你可以很容易地找到键的值(这是字典的重点). (2认同)

spe*_*der 9

在回答问题"我无法更新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);
}
Run Code Online (Sandbox Code Playgroud)

  • 更改行:foreach(键入中的int)到foreach(在dic.keys中的int i)抛出和InvalidOperationException,"集合被修改;枚举操作可能无法执行".如上所述制作副本不会以这种方式失败. (4认同)
  • 当然,但如果字典在循环中被改变,那么枚举会发生什么?它会改变,确定吗? (2认同)

Mat*_*eid 8

的foreach.有三种方法:您可以枚举Keys属性,Values属性或字典本身,它是枚举器KeyValuePair<TKey, TValue>.