What is the best way to iterate over a Dictionary in C#?

I've seen a few different ways to iterate over a Dictionary in C#. Is there a standard way?


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

If you are trying to use a generic Dictionary in C# like you would use an associative array in another language:

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

Or, if you only need to iterate over the collection of keys, use

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

And lastly, if you're only interested in the values:

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

(Take note that the var keyword is an optional C# 3.0 and above feature, you could also use the exact type of your keys/values here)


In some cases you may need a counter that may be provided by for-loop implementation. For that, LINQ provides ElementAt which enables the following:

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/798.html

上一篇: 在JavaScript中创建多行字符串

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