views:

135

answers:

8

Hi folks,

I have a quick question. Is there way to easy loop through System.Collections.Generic.Dictionary via for statement in C#?

Thanks in advance.

+6  A: 

You can use foreach:

Dictionary<string,string> dictionary = new Dictionary<string,string>();

// ...

foreach (KeyValuePair<string,string> kv in dictionary) 
{
    string key = kv.Key;
    string value = kv.Value;
}
Philippe Leybaert
That should be `foreach`.
GraemeF
Indeed, it has been fixed in the meantime
Philippe Leybaert
+1 You beat me to it Philippe.
ChrisBD
A: 

No, for is mostly for collections with indices. You can foreach over it easily, however.

Andrey Shchekin
A: 

You can loop over the keys

 for(int i = 0; i < myDictionary.Keys.Length; ++i)
      myDictionary.Keys[i] ...

or the values

 for(int i = 0; i < myDictionary.Values.Length; ++i)
      myDictionary.Values[i] ...

Or both as Philippe shows

Matt Greer
That will not compile `Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.Dictionary<TKey,TValue>KeyCollection'`
Fredrik Mörk
He was looking for: Count instead of Length, which only applies to 'normal' arrays
Oxymoron
@Oxymoron: even when using `Count`, trying to access elements in the `Keys` collection by index (`Keys[i]`) will still break the build (which was the error I was referring to in my comment).
Fredrik Mörk
A: 

If you are using Net 3.5 or later then you can use LINQ and a predecate to locate a specific Value or Values. Dictionaries do not necessarily store their KeyValue pairs in order (either by entry order nor Key order).

ChrisBD
+1  A: 

There are several ways. Looping through the keys:

foreach(var key in myDictionary.Keys)

looping through values:

foreach(var value in myDic.Values)

looping through pairs:

foreach(KeyValuePair<K, V> p in myDic)
{  
     var key = p.Key;
     var value = p.Value
}
Oxymoron
A: 

Philippe's got it for foreach, though I usually simplify it to:

foreach (var pair in dictionary) 
{
    var key = pair.Key;
    var value = pair.Value;
}

There's no way to loop through this collection of key-value pairs using a for loop because they aren't stored in order. You can loop through the keys or the values as collections though.

Keith
+1  A: 

Not in a reasonable way, no. You could use the Linq extension ElementAt:

for (int i = 0; i < dictionary.Keys.Count; i++)
{
    Console.WriteLine(dictionary.ElementAt(i).Value);                
}

...but I really don't see the point. Just use the regular foreach approach. If you for some reason need to keep track of an index while iterating, you can do that "on the side":

int index = 0;
foreach (var item in dictionary)
{
    Console.WriteLine(string.Format("[{0}] - {1}", index, item.Value));

    // increment the index
    index++;
}
Fredrik Mörk
A: 

It can ofc be done, but it is a bit silly IMO

        Dictionary<string,string> dictionary = new Dictionary<string, string>();
        Dictionary<string, string>.Enumerator enumerator = dictionary.GetEnumerator();
        for (int i = 0; i < attributeValues.Count;i++ )
        {
            KeyValuePair<string, string> current = enumerator.Current;
            //do something usefull
            enumerator.MoveNext();
        }

the only thing gained by this is a (fairly useless) index, and if that is the actual goal, you are better served by something like this:

        int currentIndex = 0;
        foreach (KeyValuePair<string, string> keyValuePair in dictionary)
        {
            //do something usefull
            currentIndex++;
        }
LaustN