iburlakov
iburlakov

Reputation: 4232

Loop through System.Collections.Generic.Dictionary via for statement

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

Thanks in advance.

Upvotes: 8

Views: 18831

Answers (9)

user4531
user4531

Reputation: 2565

If it does not have to be a "for"-loop, maybe using the Dictionary.GetEnumerator Method with a "while"-loop is an option - it is pretty easy as well IMHO:

var enumerator = d.GetEnumerator();
while (enumerator.MoveNext())
{
var pair = enumerator.Current;
b += pair.Value;
}
enumerator.Dispose();

code-snippet from C# Dictionary GetEnumerator

Upvotes: 0

LaustN
LaustN

Reputation: 720

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

Upvotes: 0

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158369

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

Upvotes: 7

Keith
Keith

Reputation: 155792

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.

Upvotes: 0

Oxymoron
Oxymoron

Reputation: 1392

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
}

Upvotes: 3

ChrisBD
ChrisBD

Reputation: 9209

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).

Upvotes: 0

Matt Greer
Matt Greer

Reputation: 62057

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

Upvotes: -1

Andrey Shchekin
Andrey Shchekin

Reputation: 21609

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

Upvotes: 0

Philippe Leybaert
Philippe Leybaert

Reputation: 171864

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

Upvotes: 12

Related Questions