什么是在C#中迭代字典的最佳方式?

我已经看到了几种不同的方法来遍历C#中的Dictionary。 有没有标准的方法?


foreach(KeyValuePair<string, string> entry in myDictionary)
{
    // do something with entry.Value or entry.Key
}

如果您正在尝试在C#中使用通用字典,就像使用其他语言的关联数组一样:

foreach(var item in myDictionary)
{
  foo(item.Key);
  bar(item.Value);
}

或者,如果您只需要迭代密钥集合,请使用

foreach(var item in myDictionary.Keys)
{
  foo(item);
}

最后,如果你只对价值感兴趣:

foreach(var item in myDictionary.Values)
{
  foo(item);
}

(请注意, var关键字是可选的C#3.0及以上版本功能,您也可以在此处使用您的键/值的确切类型)


在某些情况下,您可能需要一个可通过for-loop实现提供的计数器。 为此,LINQ提供了ElementAt ,它可以实现以下功能:

for (int index = 0; index < dictionary.Count; index++) {
  var item = dictionary.ElementAt(index);
  var itemKey = item.Key;
  var itemValue = item.Value;
}
链接地址: http://www.djcxy.com/p/797.html

上一篇: What is the best way to iterate over a Dictionary in C#?

下一篇: Iterating over dictionaries using 'for' loops