Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

loops

generics

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

Thanks in advance.

like image 289
iburlakov Avatar asked Jan 20 '10 08:01

iburlakov


People also ask

What is System collections generic dictionary?

Contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.

What is TKey and TValue?

Note that the Dictionary<TKey, TValue> has two type parameters, TKey and TValue. TKey is the type of the keys, and TValue is the type of the values (i.e., the data elements associated with the keys). Keys must always be non-null — any attempt to use a null key will result in an ArgumentNullException.

Can a for loop dictionary in C#?

We can use simple for loop to iterate over dictionary key value pairs. We can access the KeyValuePair values by dictionary index using dictionary. ElementAt() function.

Is Dictionary generic collection in C#?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.


2 Answers

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;
}
like image 92
Philippe Leybaert Avatar answered Nov 09 '22 04:11

Philippe Leybaert


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++;
}
like image 40
Fredrik Mörk Avatar answered Nov 09 '22 03:11

Fredrik Mörk