Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a dictionary?

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

like image 799
Jake Stewart Avatar asked Sep 26 '08 18:09

Jake Stewart


2 Answers

foreach(KeyValuePair<string, string> entry in myDictionary) {     // do something with entry.Value or entry.Key } 
like image 65
Pablo Fernandez Avatar answered Sep 20 '22 06:09

Pablo Fernandez


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)

like image 40
Jacob Avatar answered Sep 21 '22 06:09

Jacob