Categories
c# dictionary loops

How to iterate over a dictionary?

3081

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

11

  • 90

    @VikasGupta What would you suggest for doing something with a collection of key-value pairs when you don’t know what the keys are going to be?

    – nasch

    Feb 26, 2015 at 22:27


  • 33

    @displayName If you want to do something with each key-value pair but don’t have a reference to the keys to use to look up values, you would iterate over the dictionary, right? I was just pointing out that there could be times you would want to do that, despite Vikas’ claim that this is usually incorrect usage.

    – nasch

    Oct 28, 2015 at 18:01

  • 46

    To say that it’s incorrect usage implies that there’s a better alternative. What’s that alternative?

    Jun 20, 2017 at 21:13

  • 69

    VikasGupta is wrong, I can affirm that after many years of high-performance C# and C++ programming in non-theoretical scenarios. There are indeed frequent cases where one would create a dictionary, store unique key-value pairs, and then iterate over these values, which are proven to have unique keys within the collection. Creating any further collections is a really inefficient and costly way of avoiding dictionary iteration. Please provide a good alternative as answer to the question clarifying your point of view, otherwise your comment is pretty nonsensical.

    Aug 1, 2018 at 20:53


  • 13

    VikasGupta is 100% correct. If you have “a collection of key-value pairs” and don’t know what to do with it, you can literally put it into an ICollection<KeyValuePair> (easiest implementation: List). And if you’re concerned with “high-performance programming“, then you should be aware that the only thing Dictionaries are faster at is looking up an item via key – adding items is slower and iterating over a dictionary can easily take twice as long as iterating over a list.

    Mar 12, 2019 at 16:53


4285

foreach(KeyValuePair<string, string> entry in myDictionary)
{
    // do something with entry.Value or entry.Key
}

2

  • 1

    This is nice, but is there any concise syntax to unpack the key and value into their own variables from a KeyValuePair? E.g. in Python if I knew my keys were people’s names and my values addresses, I might write for (name, address) in myDictionary.items()

    Mar 18 at 3:23

  • 14

    @user2428107 You can use deconstruction in c# to accomplish this. foreach (var (key, value) in myDictionary)

    Mar 25 at 17:43

1034

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

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

5

  • 43

    I appreciate that this answer points out you can iterate over the keys or the values explicitly.

    Jan 13, 2015 at 6:17

  • 11

    var should be used sparingly, in my opinion. Particularly here, it is not constructive: the type KeyValuePair is likely relevant to the question.

    – Sinjai

    Aug 21, 2017 at 16:21

  • 5

    var has a unique purpose and i don’t believe it is ‘syntactic’ sugar. Using it purposefully is an appropriate approach.

    – Joshua K

    Sep 7, 2018 at 18:43

  • 1

    using var in a foreach statement is dangerous because sometimes the compiler replace “var” with “object” instead of using the proper type.

    – Maxter

    Dec 3, 2019 at 16:56

  • 1

    @JamesWierzba I would say what hurts readability is the lack of a good variable name (due to it being a demo example). In real code, had it been foreach (var vehicle in line.Values) { start(vehicle); } it would be readable just fine.

    – spectras

    Jun 11, 2020 at 11:53

184

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

11

  • 22

    To use the ‘.ElementAt’ method, remember: using System.Linq; This is not incluted in fx. auto generated test classes.

    – Tinia

    Nov 24, 2011 at 14:47


  • 14

    This is the way to go if you are modifying the values associated with the keys. Otherwise an exception is thrown when modifying and using foreach().

    Apr 3, 2013 at 7:18

  • 38

    Isn’t ElementAt a O(n) operation?

    Feb 7, 2015 at 1:46

  • 190

    This answer is completely undeserving of so many upvotes. A dictionary has no implicit order, so using .ElementAt in this context might lead to subtle bugs. Far more serious is Arturo’s point above. You’ll be iterating the dictionary dictionary.Count + 1 times leading to O(n^2) complexity for an operation that should only be O(n). If you really need an index (if you do, you’re probably using the wrong collection type in the first place), you should iterate dictionary.Select( (kvp, idx) => new {Index = idx, kvp.Key, kvp.Value}) instead and not use .ElementAt inside the loop.

    – spender

    Mar 2, 2015 at 2:17


  • 12

    ElementAt – o(n) operation! Seriously? This is the example of how you should not do it. These many upvotes?

    May 12, 2016 at 22:14