By Jake Stewart


2008-09-26 18:20:06 8 Comments

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

25 comments

@BigChief 2018-08-19 20:50:39

in addition to the highest ranking posts where there is a discussion between using

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

or

foreach(var entry in myDictionary)
{
    // do something with entry.Value or entry.Key
}

most complete is the following because you can see the dictionary type from the initialization, kvp is KeyValuePair

var myDictionary = new Dictionary<string, string>(x);//fill dictionary with x

foreach(var kvp in myDictionary)//iterate over dictionary
{
    // do something with kvp.Value or kvp.Key
}

@Matthew Goulart 2018-09-06 19:23:40

Creating and copying a second dictionary is not a valid solution to code readability. In fact, I would argue it would make the code harder to understand because now you have to ask yourself: "Why did the last guy create a second dictionary?" If you want to be more verbose, just use option one.

@BigChief 2018-09-08 09:03:50

I just meant to show you that when decl dict before for each, usage in the foreach is clear from the declaration

@sɐunıɔןɐqɐp 2018-05-27 12:25:49

Using C# 7, add this extension method to any project of your solution:

public static class IDictionaryExtensions
{
    public static IEnumerable<(TKey, TValue)> Tuples<TKey, TValue>(
        this IDictionary<TKey, TValue> dict)
    {
        foreach (KeyValuePair<TKey, TValue> kvp in dict)
            yield return (kvp.Key, kvp.Value);
    }
}


And use this simple syntax

foreach (var(id, value) in dict.Tuples())
{
    // your code using 'id' and 'value'
}


Or this one, if you prefer

foreach ((string id, object value) in dict.Tuples())
{
    // your code using 'id' and 'value'
}


In place of the traditional

foreach (KeyValuePair<string, object> kvp in dict)
{
    string id = kvp.Key;
    object value = kvp.Value;

    // your code using 'id' and 'value'
}


The extension method transforms the KeyValuePair of your IDictionary<TKey, TValue> into a strongly typed tuple, allowing you to use this new comfortable syntax.

It converts -just- the required dictionary entries to tuples, so it does NOT converts the whole dictionary to tuples, so there are no performance concerns related to that.

There is a only minor cost calling the extension method for creating a tuple in comparison with using the KeyValuePair directly, which should NOT be an issue if you are assigning the KeyValuePair's properties Key and Value to new loop variables anyway.

In practice, this new syntax suits very well for most cases, except for low-level ultra-high performance scenarios, where you still have the option to simply not use it on that specific spot.

Check this out: MSDN Blog - New features in C# 7

@Maarten 2018-09-10 12:57:33

What would be the reason to prefer 'comfortable' tuples to key-value-pair's? I don't see a gain here. Your tuple contains a key and a value, so does the key-value-pair.

@sɐunıɔןɐqɐp 2018-09-10 13:49:21

Hi Maarten, thanks for your question. The main benefit is code readability without additional programming effort. With KeyValuePair one must always use the form kvp.Key and kvp.Value for using respectively key and value. With tuples you get the flexibility to name the key and the value as you wish, without using further variable declarations inside the foreach block. E.g. you may name your key as factoryName, and the value as models, which is especially useful when you get nested loops (dictionaries of dictionaries): code maintenance gets much easier. Just give it a try! ;-)

@Domn Werner 2018-07-11 18:05:23

As of C# 7, you can deconstruct objects into variables. I believe this to be the best way to iterate over a dictionary.

Example:

Create an extension method on KeyValuePair<TKey, TVal> that deconstructs it:

public static void Deconstruct<TKey, TVal>(this KeyValuePair<TKey, TVal> pair, out TKey, out TVal val)
{
   key = pair.Key;
   val = pair.Value;
}

Iterate over any Dictionary<TKey, TVal> in the following manner

// Dictionary can be of any types, just using 'int' and 'string' as examples.
Dictionary<int, string> dict = new Dictionary<int, string>();

// Deconstructor gets called here.
foreach (var (key, value) in dict)
{
   Console.WriteLine($"{key} : {value}");
}

@Maurício Fedatto 2011-03-10 20:44:43

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

@Tinia 2011-11-24 14:47:37

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

@Mike de Klerk 2013-04-03 07:18:23

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

@RenniePet 2014-01-14 18:54:38

Be careful when using this. See here: stackoverflow.com/a/2254480/253938

@zionpi 2015-01-21 09:03:30

This is useful when you want to modify while iterate.The foreach version will throw exception while you enumerate the collection.

@Arturo Torres Sánchez 2015-02-07 01:46:14

Isn't ElementAt a O(n) operation?

@spender 2015-03-02 02:17:05

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.

@Ian Ringrose 2015-09-24 14:46:53

I expect this will be very slow for large dictionaries.

@Neil 2016-02-09 00:03:17

@MikedeKlerk, modifying the dictionary while iterating it is not safe. See the comments under stackoverflow.com/a/31112746/24315.

@Mukesh Adhvaryu 2016-05-12 22:14:44

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

@Jeppe Stig Nielsen 2016-06-05 15:21:43

@spender Agree. Of course, an alternative is var dictCopy = dictionary.ToArray(); (again using a Linq extension), and the you can access dictCopy by array index afterwards.

@Padmika 2016-10-06 23:20:51

The O(n^2) complexity will make this slow for large collections

@Steven Delrue 2018-06-08 07:07:02

I wrote an extension to loop over a dictionary.

public static class DictionaryExtension
{
    public static void ForEach<T1, T2>(this Dictionary<T1, T2> dictionary, Action<T1, T2> action) {
        foreach(KeyValuePair<T1, T2> keyValue in dictionary) {
            action(keyValue.Key, keyValue.Value);
        }
    }
}

Then you can call

myDictionary.ForEach((x,y) => Console.WriteLine(x + " - " + y));

@George Mauer 2008-09-26 18:22:25

I would say foreach is the standard way, though it obviously depends on what you're looking for

foreach(var kvp in my_dictionary) {
  ...
}

Is that what you're looking for?

@RenniePet 2014-01-11 12:09:04

Um, isn't naming the item "value" rather confusing? You would typically be using syntax like "value.Key" and "value.Value", which isn't very intuitive for anyone else who will be reading the code, especially if they aren't familiar with how the .Net Dictionary is implemented.

@mbx 2016-03-09 16:10:49

@RenniePet kvp is commonly used to name KeyValuePair instances when iterating over dictionaries and related data structures: foreach(var kvp in myDictionary){....

@Liath 2014-07-30 10:54:42

I appreciate this question has already had a lot of responses but I wanted to throw in a little research.

Iterating over a dictionary can be rather slow when compared with iterating over something like an array. In my tests an iteration over an array took 0.015003 seconds whereas an iteration over a dictionary (with the same number of elements) took 0.0365073 seconds that's 2.4 times as long! Although I have seen much bigger differences. For comparison a List was somewhere in between at 0.00215043 seconds.

However, that is like comparing apples and oranges. My point is that iterating over dictionaries is slow.

Dictionaries are optimised for lookups, so with that in mind I've created two methods. One simply does a foreach, the other iterates the keys then looks up.

public static string Normal(Dictionary<string, string> dictionary)
{
    string value;
    int count = 0;
    foreach (var kvp in dictionary)
    {
        value = kvp.Value;
        count++;
    }

    return "Normal";
}

This one loads the keys and iterates over them instead (I did also try pulling the keys into a string[] but the difference was negligible.

public static string Keys(Dictionary<string, string> dictionary)
{
    string value;
    int count = 0;
    foreach (var key in dictionary.Keys)
    {
        value = dictionary[key];
        count++;
    }

    return "Keys";
}

With this example the normal foreach test took 0.0310062 and the keys version took 0.2205441. Loading all the keys and iterating over all the lookups is clearly a LOT slower!

For a final test I've performed my iteration ten times to see if there are any benefits to using the keys here (by this point I was just curious):

Here's the RunTest method if that helps you visualise what's going on.

private static string RunTest<T>(T dictionary, Func<T, string> function)
{            
    DateTime start = DateTime.Now;
    string name = null;
    for (int i = 0; i < 10; i++)
    {
        name = function(dictionary);
    }
    DateTime end = DateTime.Now;
    var duration = end.Subtract(start);
    return string.Format("{0} took {1} seconds", name, duration.TotalSeconds);
}

Here the normal foreach run took 0.2820564 seconds (around ten times longer than a single iteration took - as you'd expect). The iteration over the keys took 2.2249449 seconds.

Edited To Add: Reading some of the other answers made me question what would happen if I used Dictionary instead of Dictionary. In this example the array took 0.0120024 seconds, the list 0.0185037 seconds and the dictionary 0.0465093 seconds. It's reasonable to expect that the data type makes a difference on how much slower the dictionary is.

What are my Conclusions?

  • Avoid iterating over a dictionary if you can, they are substantially slower than iterating over an array with the same data in it.
  • If you do choose to iterate over a dictionary don't try to be too clever, although slower you could do a lot worse than using the standard foreach method.

@Even Mien 2015-02-23 19:26:09

You should measure with something like StopWatch instead of DateTime: hanselman.com/blog/…

@WiiMaxx 2015-07-29 08:57:13

could you please describe your test scenario, how many items where in your dictionary, how often did you run your scenario to calculate the average time, ...

@Martin Brown 2016-06-30 08:36:25

Interestingly you will get different results depending upon what data you have in the dictionary. While itterating over the Dictionary the Enumerator function has to skip a lot of empty slots in the dictionary which is what causes it to be slower than iterating over an array. If the Dictionary is full up there will be less empty slots to skip than if it is half empty.

@Sheo Dayal Singh 2018-04-16 11:25:37

Dictionary< TKey, TValue > It is a generic collection class in c# and it stores the data in the key value format.Key must be unique and it can not be null whereas value can be duplicate and null.As each item in the dictionary is treated as KeyValuePair< TKey, TValue > structure representing a key and its value. and hence we should take the element type KeyValuePair< TKey, TValue> during the iteration of element.Below is the example.

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1,"One");
dict.Add(2,"Two");
dict.Add(3,"Three");

foreach (KeyValuePair<int, string> item in dict)
{
    Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}

@theo 2008-09-26 18:22:47

There are plenty of options. My personal favorite is by KeyValuePair

Dictionary<string, object> myDictionary = new Dictionary<string, object>();
// Populate your dictionary here

foreach (KeyValuePair<string,object> kvp in myDictionary)
{
     // Do some interesting things
}

You can also use the Keys and Values Collections

@J Healy 2008-09-26 18:27:49

Depends on whether you're after the keys or the values...

From the MSDN Dictionary(TKey, TValue) Class description:

// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
    Console.WriteLine("Key = {0}, Value = {1}", 
        kvp.Key, kvp.Value);
}

// To get the values alone, use the Values property.
Dictionary<string, string>.ValueCollection valueColl =
    openWith.Values;

// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach( string s in valueColl )
{
    Console.WriteLine("Value = {0}", s);
}

// To get the keys alone, use the Keys property.
Dictionary<string, string>.KeyCollection keyColl =
    openWith.Keys;

// The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
Console.WriteLine();
foreach( string s in keyColl )
{
    Console.WriteLine("Key = {0}", s);
}

@Amit Kumar Verma 2018-03-09 06:02:43

Dictionaries are special lists, whereas every value in the list has a key which is also a variable. A good example of a dictionary is a phone book.

   Dictionary<string, long> phonebook = new Dictionary<string, long>();
    phonebook.Add("Alex", 4154346543);
    phonebook["Jessica"] = 4159484588;

Notice that when defining a dictionary, we need to provide a generic definition with two types - the type of the key and the type of the value. In this case, the key is a string whereas the value is an integer.

There are also two ways of adding a single value to the dictionary, either using the brackets operator or using the Add method.

To check whether a dictionary has a certain key in it, we can use the ContainsKey method:

Dictionary<string, long> phonebook = new Dictionary<string, long>();
phonebook.Add("Alex", 415434543);
phonebook["Jessica"] = 415984588;

if (phonebook.ContainsKey("Alex"))
{
    Console.WriteLine("Alex's number is " + phonebook["Alex"]);
}

To remove an item from a dictionary, we can use the Remove method. Removing an item from a dictionary by its key is fast and very efficient. When removing an item from a List using its value, the process is slow and inefficient, unlike the dictionary Remove function.

Dictionary<string, long> phonebook = new Dictionary<string, long>();
phonebook.Add("Alex", 415434543);
phonebook["Jessica"] = 415984588;

phonebook.Remove("Jessica");
Console.WriteLine(phonebook.Count);

@Pablo Fernandez 2008-09-26 18:22:10

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

@Ozair Kafray 2016-01-05 07:32:50

What if I don't exactly know the type of key/value in Dictionary. Using var entry is better in that case, and thus i did vote this answer on a second look instead of the above one.

@Nate 2016-01-25 23:34:44

@OzairKafray using var when you don't know the type is generally bad practice.

@Septagram 2016-04-18 16:17:08

@Nate and if I do know the type, but don't want an extra boilerplate? Is this code faster, or does it not matter?

@MonkeyWrench 2016-05-17 17:19:20

This answer is superior because Pablo didn't default to the lazy coder "var" usage that obfuscates the return type.

@Robert Harvey 2016-12-09 18:30:18

@MonkeyWrench: Meh. Visual Studio knows what the type is; all you have to do is hover over the variable to find out.

@quemeful 2017-02-07 15:58:47

this answer is good. if you came here knowing what a dictionary is, and the concept of iterating, you should be able to figure out how to use a loop

@Kyle Delaney 2017-09-21 13:06:01

As I understand it, var only works if the type is known at compile time. If Visual Studio knows the type then it's available for you to find out as well.

@Bengalaa 2017-10-04 19:22:39

does somebody know the algorithmic complexity of this solution?

@TheAtomicOption 2017-10-27 21:50:28

@Bengalaa I would be very surprised if it's not O(1).

@Jeppe Stig Nielsen 2017-11-20 09:39:45

One important reason why you should always use var in a foreach statement is because if you do not, it is hard to see if there is an explicit cast hidden in the syntax or not, a cast that may fail! This does not happen when the compile-time type of myDic is a generic Dictionary<,> because the compile-time type of Current is then a struct which allows no such casts. But set IDictionary myDic2 = myDic;, then foreach(KeyValuePair<string, string> entry in myDic2) will compile but will throw when run (unless myDic is empty). Also: IList<IAnimal> s = ...; foreach (IPlant p in s) {}

@AaA 2017-12-29 01:37:38

@JeppeStigNielsen, Lets say I used var in foreach, are you planning to use its key and values later or just iterating? if you are planning to use it later, you need to know the actual type of the variable, unless all your variables are declared as vars! Strict type declaration makes it easier to read the code in email, notepad, version control too which also do not have IntelliSense.I agree with nate and MonkeyRench

@Jeppe Stig Nielsen 2017-12-29 09:25:42

@AaA Almost always we use the foreach iteration variable inside the loop body. If you want Notepad-friendly code, I suggest you type the exact same type as IntelliSense infers when you use var. Then if you need a cast, write it explicitly. That is just my opinion, of course.

@Gusdor 2018-01-14 00:19:46

Am I crazy for only ever using var for linq queries, anonysmous types and assignments that end with a constructor call? Maximises readability, avoids runtime side effects.

@Aluan Haddad 2018-01-22 14:02:14

@Gusdor var does not have any impact on runtime behavior. And yes, you are crazy :) <3

@Gusdor 2018-01-22 14:30:02

@AluanHaddad consider this code: var items = externalLibrary.GetItems(filestream); You close the stream and loop over the collection. In the new version of 'External Library', the return type of GetItems is changed from List<string> to IEnumerable<string>. BANG, exception. The file is being accessed after you closed the stream. Runtime behaviour has changed because you were too lazy to type IList<string>. Why wait for tests to find this when your compiler can do it?

@Aluan Haddad 2018-01-22 15:18:52

@Gusdor var is often more about readability than writability. When I read a method I want to start by getting a high level understanding. Then I dig into the details if necessary. In your example, the change in return type does not imply that the underlying implementation is lazy. Anyway, such APIs are awkward to work with because it is already unclear who is responsible for disposing the stream. Anyway, I am not saying to never use an explicit type, I am saying that I prefer var almost everywhere. Java makes my eyes bleed when I have to read it, not just write it.

@Gusdor 2018-01-22 15:35:08

@AluanHaddad I just described to you how readability can impact the correctness of your software over time....I also agree that code is read more than it is written and yet, var is less readable. Why would stripping away all meaning ever be more readable? Consider var userInfo = service.GetUser();. What type is userInfo? You don't know without intellisense. If you were viewing this on Github's web interface it will be a pain to navigate.

@Aluan Haddad 2018-01-22 15:37:53

@Gusdor we are verging on a holy war here ;). Honestly, I do not want to know or think about what the type is. I just want to know that it is some representation of a user. Anyway, the choice is yours and mine. I find var to be more readable.

@Zev Spitz 2018-01-24 01:26:31

@Gusdor Isn't this a breaking change? I would expect the authors of 'External Library' to be responsible enough to describe it in the release notes, so I could find all references to GetItems in my code and change it accordingly. And if the authors are not responsible enough to do that, then it is time to find a new 'External Library'.

@Zev Spitz 2018-01-24 01:35:31

@Gusdor Consider var userInfo = service.GetUser();. What type is userInfo? -- The answer is, when do I care? When I am writing the code in Visual Studio, I need to be aware of the properties and methods made available to me from the type. On GitHub, I probably should avoid editing the code without the safety net of VS, the compiler, and Intellisense. For reading code on GitHub, I think it's a better practice to insist that only compiling code should be synced to GitHub, and thus I have enough information about userInfo from the surrounding code's use of its properties and methods ...

@Zev Spitz 2018-01-24 01:39:27

... to get a good idea of what it is, even if I don't know the exact type. In that scenario, actually having the concrete type name obscures the intent of the code -- userInfo is an instance of MyCompany.MyProject.InnerNamespace.UserDetails; without browsing to the appropriate file (and I have no Goto Reference on GitHub, so I'll have to find it by hand) this adds virtually no information; and so the name becomes another bit of noise I have to parse while reading. Just my 2 cents.

@fixagon 2018-02-07 14:10:32

@Bengalaa its O(n) not O(1)

@jinavar1 2018-05-08 21:22:31

The way I do it: I configure .editorconfig with rule csharp_style_var_for_built_in_types = false : error, then I use var on purpose and then I let VisualStudio tell me it's wrong and I let it fix it for me. It's way faster.

@dynamichael 2018-06-10 14:10:06

Gee whiz, people... "var" compiles to the actual type at compile time—it's simply there for the coder's convenience. That way, if you need to change the type, it's fewer places you have to do it.

@sɐunıɔןɐqɐp 2018-08-02 08:29:25

@MonkeyWrench: If type is not known by the programmer, he may just use var, and then immediately use quick actions to convert the var to the explicit type. See: Micrososoft's webpage. Good practice and var combined together.

@Alex Logan 2018-08-17 14:11:18

If you don't like var then just use Java

@AminM 2018-10-12 09:18:22

i am 3000 repu,but why don't use var??

@Pavel 2017-10-17 15:18:55

With .NET Framework 4.7 one can use decomposition

var fruits = new Dictionary<string, int>();
...
foreach (var (fruit, number) in fruits)
{
    Console.WriteLine(fruit + ": " + number);
}

To make this code work on lower C# versions, add System.ValueTuple NuGet package and write somewhere

public static class MyExtensions
{
    public static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> tuple,
        out T1 key, out T2 value)
    {
        key = tuple.Key;
        value = tuple.Value;
    }
}

@David Arno 2017-10-18 11:58:34

This is incorrect. .NET 4.7 simply has ValueTuple built in. It's available as a nuget package for earlier versions. More importantly, C# 7.0+ is needed for the Deconstruct method to work as a deconstructor for var (fruit, number) in fruits.

@Ron 2016-10-02 04:00:41

Simplest form to iterate a dictionary:

foreach(var item in myDictionary)
{ 
    Console.WriteLine(item.Key);
    Console.WriteLine(item.Value);
}

@Stéphane Gourichon 2015-08-10 11:15:17

Generally, asking for "the best way" without a specific context is like asking what is the best color.

One the one hand, there are many colors and there's no best color. It depends on the need and often on taste, too.

On the other hand, there are many ways to iterate over a Dictionary in C# and there's no best way. It depends on the need and often on taste, too.

Most straightforward way

foreach (var kvp in items)
{
    // key is kvp.Key
    doStuff(kvp.Value)
}

If you need only the value (allows to call it item, more readable than kvp.Value).

foreach (var item in items.Values)
{
    doStuff(item)
}

If you need a specific sort order

Generally, beginners are surprised about order of enumeration of a Dictionary.

LINQ provides a concise syntax that allows to specify order (and many other things), e.g.:

foreach (var kvp in items.OrderBy(kvp => kvp.Key))
{
    // key is kvp.Key
    doStuff(kvp.Value)
}

Again you might only need the value. LINQ also provides a concise solution to:

  • iterate directly on the value (allows to call it item, more readable than kvp.Value)
  • but sorted by the keys

Here it is:

foreach (var item in items.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))
{
    doStuff(item)
}

There are many more real-world use case you can do from these examples. If you don't need a specific order, just stick to the "most straightforward way" (see above)!

@Mafii 2016-09-23 10:05:34

The last one should be .Values and not a select clause.

@Stéphane Gourichon 2016-09-23 14:30:16

@Mafii Are you sure? Values returned by OrderBy are not of a KeyValuePair type, they have no Value field. Exact type I see here is IOrderedEnumerable<KeyValuePair<TKey, TValue>>. Perhaps you meant something else? Can you write a complete line showing what you mean (and test it)?

@Mafii 2016-09-23 14:34:22

I think this answer contains what I mean: stackoverflow.com/a/141105/5962841 but correct me if I confused something

@Mafii 2016-09-23 15:07:43

No, read the end. There is a .Keys and a .Values property. No need to query with select...

@Stéphane Gourichon 2016-09-23 15:14:18

@Mafii Re-read my whole answer, explanations between code sections tell the context. The answer you mention is like second code section in my answer (no order required). There I just wrote items.Value like you suggested. In the case of the fourth section that you commented, the Select() is a way to cause foreach to enumerate directly on the values in the dictionary instead of key-value pairs. If somehow you don't like the Select() in this case, you might prefer the third code section. The point of the fourth section is to show that one can pre-process the collection with LINQ.

@Mafii 2016-09-23 15:18:02

What about .Keys.Orderby... ?

@Stéphane Gourichon 2016-09-23 15:23:31

If you do .Keys.Orderby() you'll iterate on a list of keys. If that's all you need, fine. If you need values, then in the loop you'd have to query the dictionary on each key to get the value. In many scenarios it won't make a practical difference. In high-performance scenario, it will. Like I wrote in the beginning of the answer: "there are many ways (...) and there's no best way. It depends on the need and often on taste, too."

@Mafii 2016-09-23 15:24:51

Well, you could also .Values.Orderby. just my 5 Cents ;) i agree tho, it doesnt really matter.

@Stéphane Gourichon 2016-09-23 15:32:29

@Alex 2016-09-16 16:03:08

Just wanted to add my 2 cent, as the most answers relate to foreach-loop. Please, take a look at the following code:

Dictionary<String, Double> myProductPrices = new Dictionary<String, Double>();

//Add some entries to the dictionary

myProductPrices.ToList().ForEach(kvP => 
{
    kvP.Value *= 1.15;
    Console.Writeline(String.Format("Product '{0}' has a new price: {1} $", kvp.Key, kvP.Value));
});

Altought this adds a additional call of '.ToList()', there might be a slight performance-improvement (as pointed out here foreach vs someList.Foreach(){}), espacially when working with large Dictionaries and running in parallel is no option / won't have an effect at all.

Also, please note that you wont be able to assign values to the 'Value' property inside a foreach-loop. On the other hand, you will be able to manipulate the 'Key' as well, possibly getting you into trouble at runtime.

When you just want to "read" Keys and Values, you might also use IEnumerable.Select().

var newProductPrices = myProductPrices.Select(kvp => new { Name = kvp.Key, Price = kvp.Value * 1.15 } );

@Servy 2016-09-16 16:08:11

Copying the entire collection for no reason at all will not improve performance. It'll dramatically slow down the code, as well as doubling the memory footprint of code that ought to consume virtually no additional memory.

@user2864740 2017-03-28 22:30:45

I avoid the side-effect 'List.ForEach' method: foreach forces side-effect visibility up, where it belongs.

@Nick 2016-07-28 10:58:55

The standard way to iterate over a Dictionary, according to official documentation on MSDN is:

foreach (DictionaryEntry entry in myDictionary)
{
     //Read entry.Key and entry.Value here
}

@sɐunıɔןɐqɐp 2018-07-23 09:26:02

This doesn't work for Dictionaries implementing generics...

@Onur 2015-06-11 13:32:27

You can also try this on big dictionaries for multithreaded processing.

dictionary
.AsParallel()
.ForAll(pair => 
{ 
    // Process pair.Key and pair.Value here
});

@Mafii 2016-09-23 10:07:50

@WiiMaxx and more important if these items do NOT depend on each other

@Pixar 2015-05-28 15:00:10

var dictionary = new Dictionary<string, int>
{
    { "Key", 12 }
};

var aggregateObjectCollection = dictionary.Select(
    entry => new AggregateObject(entry.Key, entry.Value));

@Marc L. 2017-12-29 16:37:24

There needs to be more justification/description in this answer. What does AggregateObject add to KeyValuePair? Where is the "iteration," as requested in the question?

@Pixar 2018-06-02 18:37:37

Select iterates over dictionary and allows us to work on each object. It is not as general as foreach, but I've used it a lot. Did my answer truly deserve downvote?

@Marc L. 2018-06-04 16:11:01

No, Select uses iteration to effect the result, but is not an iterator itself. The types of things that iteration (foreach) is used for--especially operations with side-effects--are outside the scope of Linq, including Select. The lambda will not run until aggregateObjectCollection is actually enumerated. If this answer is taken as a "first path" (i.e., used before a straight foreach) it encourages bad practices. Situationally, there may Linq operations that are helpful before iterating a dictionary, but that doesn't address the question as asked.

@Jacob 2008-09-26 18:22:42

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)

@nawfal 2013-11-01 14:26:01

the var feature is most required for your first code block :)

@Rotsiser Mho 2015-01-13 06:17:21

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

@James Wierzba 2017-01-25 17:23:39

I don't like the use of var here. Given that it is just syntactic sugar, why use it here? When someone is trying to read the code, they will have to jump around the code to determine the type of myDictionary (unless that is the actual name of course). I think using var is good when the type is obvious e.g. var x = "some string" but when it is not immediately obvious I think it's lazy coding that hurts the code reader/reviewer

@Sinjai 2017-08-21 16:21:44

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

@Joshua K 2018-09-07 18:43:45

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

@yazanpro 2014-10-01 23:17:52

I will take the advantage of .NET 4.0+ and provide an updated answer to the originally accepted one:

foreach(var entry in MyDic)
{
    // do something with entry.Value or entry.Key
}

@ender 2014-07-02 01:55:08

Sometimes if you only needs the values to be enumerated, use the dictionary's value collection:

foreach(var value in dictionary.Values)
{
    // do something with entry.Value only
}

Reported by this post which states it is the fastest method: http://alexpinsker.blogspot.hk/2010/02/c-fastest-way-to-iterate-over.html

@Jaanus Varus 2015-08-05 10:25:26

+1 for bringing performance in. Indeed, iterating over the dictionary itself does include some overhead if all you need are values. That is mostly due to copying values or references into KeyValuePair structs.

@Crescent Fresh 2018-07-13 14:15:04

FYI the last test in that link is test the wrong thing: it measures iterating over the keys, disregarding values, whereas the previous two tests do use the value.

@Khushi 2009-10-28 20:49:36

You suggested below to iterate

Dictionary<string,object> myDictionary = new Dictionary<string,object>();
//Populate your dictionary here

foreach (KeyValuePair<string,object> kvp in myDictionary) {
    //Do some interesting things;
}

FYI, foreach doesn't work if the value are of type object.

@Marc L. 2017-12-29 16:22:59

Please elaborate: foreach will not work if which value is of type object? Otherwise this doesn't make much sense.

@Zannjaminderson 2009-02-17 23:51:39

I found this method in the documentation for the DictionaryBase class on MSDN:

foreach (DictionaryEntry de in myDictionary)
{
     //Do some stuff with de.Value or de.Key
}

This was the only one I was able to get functioning correctly in a class that inherited from the DictionaryBase.

@joedotnot 2014-04-26 13:21:36

This looks like when using the non-generics version of Dictionary... i.e. prior to .NET framework 2.0.

@sɐunıɔןɐqɐp 2018-08-01 19:42:55

@joed0tnot : it is the non-generics version used for Hashtable objects

@mzirino 2008-12-09 04:16:11

If say, you want to iterate over the values collection by default, I believe you can implement IEnumerable<>, Where T is the type of the values object in the dictionary, and "this" is a Dictionary.

public new IEnumerator<T> GetEnumerator()
{
   return this.Values.GetEnumerator();
}

@sɐunıɔןɐqɐp 2018-07-23 09:27:14

This doesn't explain much about how to iterate...

Related Questions

Sponsored Content

49 Answered Questions

[SOLVED] How to merge two dictionaries in a single expression?

41 Answered Questions

[SOLVED] How do I sort a dictionary by value?

56 Answered Questions

[SOLVED] What is the difference between String and string in C#?

20 Answered Questions

[SOLVED] Add new keys to a dictionary?

  • 2009-06-21 22:07:39
  • lfaraone
  • 2520515 View
  • 2035 Score
  • 20 Answer
  • Tags:   python dictionary

28 Answered Questions

[SOLVED] For-each over an array in JavaScript?

11 Answered Questions

[SOLVED] Iterating over dictionaries using 'for' loops

38 Answered Questions

[SOLVED] How to efficiently iterate over each entry in a Java Map?

10 Answered Questions

19 Answered Questions

[SOLVED] Check if a given key already exists in a dictionary

  • 2009-10-21 19:05:09
  • Mohan Gulati
  • 2448502 View
  • 2365 Score
  • 19 Answer
  • Tags:   python dictionary

7 Answered Questions

[SOLVED] Iterate through a HashMap

Sponsored Content