Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What is the best way to iterate over a dictionary?

I've seen various methods to iterate over a dictionary in C#. Is there a regular way?
by

2 Answers

sandhya6gczb
There iterate of dictionary in C# use

foreach (KeyValuePair item in myDictionary)
{
MessageBox.Show(item.Key + " " + item.Value);
}

We can also use loops as sometime we need to keep track of counter values.

for (int count = 0; count < myDictionary.Count; count++)
{
var element = myDictionary.ElementAt(count);
var Key = element.Key;
var Value = element.Value;
MessageBox.Show(Key + " " + Value);
}

MounikaDasa
In some cases you may need a counter that may be provided by for-loop implementation. For that, LINQ provides ElementAt which enables the following:

for (int index = 0; index < dictionary.Count; index++) {
var item = dictionary.ElementAt(index);
var itemKey = item.Key;
var itemValue = item.Value;
}

Login / Signup to Answer the Question.