views:

25173

answers:

10

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

A: 

It entirely depends on what you're looking for. There are collections for both the Keys and the Values so that you can iterate over either one depending your your needs.

Orion Adrian
And don't forget that you can also iterate over the pairs, i.e. keys and values together :)
OregonGhost
+51  A: 
  foreach(KeyValuePair<String,String> entry in MyDic)
  {
      // do something with entry.Value or entry.Key
  }
Pablo Fernandez
I'd use `var` instead of `KeyValuePair<String, String>` though...
Svish
@Svish `var` is 3.0 and greater only
Pablo Fernandez
@Pablo: I know. And I'd still use it. And if I couldn't, I'd fight for the right to. (And as far as I know, you can actually use it even though you are not targeting 3.0 or later. http://weblogs.asp.net/shahar/archive/2008/01/23/use-c-3-features-from-c-2-and-net-2-0-code.aspx)
Svish
@Svish actually that's an Visual Studio 2008 thing. I'd definitely use `var` if available, but my solution is platform-wide.
Pablo Fernandez
@Pablo: Of course. I was just saying :)
Svish
@Pablo: So .Net implicitly targets KeyValuePair type? Is it possible that would var would reference the value instead of the KeyValuePair or possibly the key?
jlafay
Yes. If you want to iterate over the keys you can do `foreach(var key in MyDic.Keys)`
Pablo Fernandez
+4  A: 

I would say foreach is the standard way, though it obviously depends on what you're looking for

foreach(var value in my_dictionary) {
  ...
}

Is that what you're looking for?

George Mauer
var is available in 3.0 and higher only
Pablo Fernandez
good point, but just use the proper type then
George Mauer
+13  A: 

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

foreach(KeyValuePair<string, string> 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 feature, you could also use the exact type of your keys/values here)

Jacob
+4  A: 

There are plenty of options. My personal favorite is by KeyValuePair

Dictionary<string,object> myDictionary = new Dictionary<string,object>();
//Populate your dictionary here

Foreach (KeyValuePair<string,object> kvp in myDictionary)
{
     //Do some interesting things;
}

You can also use the Keys and Values Collections

theo
A: 

Use the built in support for the iterator pattern, the foreach key word.

If using a non generic Dictionary, simply use the KeyValuePair type for the different items:

foreach(KeyValuePair item in myDictionary)
{
    DoStuffWith(item);
}

The generic version is almost identical, apart from defining the types in the KeyValuePair to be the same as the dictionary:

foreach(KeyValuePair<Tkey, Tvalue> item in myDictionary)
{
    DoStuffWith(item);
}
Oded
note that you can't modify 'item'
serhio
+13  A: 

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

From the MSDN Dictionary<(Of <(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);
    }
J Healy
A: 

If say, you want to iterate over the values collection by default, I believe you can implement IEnumerable<>, Where T is the type of the values object in the dictionary, and "this" is a Dictionary.

public new IEnumerator<T> GetEnumerator()
{
   return this.Values.GetEnumerator();
}
A: 

I found this method in the documentation for the DictionaryBase class on MSDN:

foreach (DictionaryEntry de in myDictionary)
{
     //Do some stuff with de.Value or de.Key
}

This was the only one I was able to get functioning correctly in a class that inherited from the DictionaryBase.

+2  A: 

You suggested below to iterate

Dictionary<string,object> myDictionary = new Dictionary<string,object>();
//Populate your dictionary here

foreach (KeyValuePair<string,object> kvp in myDictionary) {
    //Do some interesting things;
}

FYI, foreach doesn't work if the value are of type object.

Khushi