c# - How to iterate over a dictionary?

ID : 203

viewed : 391

Tags : c#dictionaryloopsc#

Top 5 Answer for c# - How to iterate over a dictionary?

vote vote

98

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

86

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)

vote vote

71

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; } 
vote vote

60

Depends on whether you're after the keys or the values...

From the MSDN Dictionary(TKey, TValue) Class description:

// When you use foreach to enumerate dictionary elements, // the elements are retrieved as KeyValuePair objects. Console.WriteLine(); foreach( KeyValuePair<string, string> kvp in openWith ) {     Console.WriteLine("Key = {0}, Value = {1}",          kvp.Key, kvp.Value); }  // To get the values alone, use the Values property. Dictionary<string, string>.ValueCollection valueColl =     openWith.Values;  // The elements of the ValueCollection are strongly typed // with the type that was specified for dictionary values. Console.WriteLine(); foreach( string s in valueColl ) {     Console.WriteLine("Value = {0}", s); }  // To get the keys alone, use the Keys property. Dictionary<string, string>.KeyCollection keyColl =     openWith.Keys;  // The elements of the KeyCollection are strongly typed // with the type that was specified for dictionary keys. Console.WriteLine(); foreach( string s in keyColl ) {     Console.WriteLine("Key = {0}", s); } 
vote vote

55

Generally, asking for "the best way" without a specific context is like asking what is the best color?

One the one hand, there are many colors and there's no best color. It depends on the need and often on taste, too.

On the other hand, there are many ways to iterate over a Dictionary in C# and there's no best way. It depends on the need and often on taste, too.

Most straightforward way

foreach (var kvp in items) {     // key is kvp.Key     doStuff(kvp.Value) } 

If you need only the value (allows to call it item, more readable than kvp.Value).

foreach (var item in items.Values) {     doStuff(item) } 

If you need a specific sort order

Generally, beginners are surprised about order of enumeration of a Dictionary.

LINQ provides a concise syntax that allows to specify order (and many other things), e.g.:

foreach (var kvp in items.OrderBy(kvp => kvp.Key)) {     // key is kvp.Key     doStuff(kvp.Value) } 

Again you might only need the value. LINQ also provides a concise solution to:

  • iterate directly on the value (allows to call it item, more readable than kvp.Value)
  • but sorted by the keys

Here it is:

foreach (var item in items.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value)) {     doStuff(item) } 

There are many more real-world use case you can do from these examples. If you don't need a specific order, just stick to the "most straightforward way" (see above)!

Top 3 video Explaining c# - How to iterate over a dictionary?

Related QUESTION?