Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over Dictionary with foreach, in what order is this done?

Say I have a Dictionary, and I add each key and value entry in a specific order.
Now, if I want later to be able to iterate this Dictionary in the same order entries were added, is it the order I get with simple foreach loop on this dictionary?

If not, I will be glad to hear how can I do that, I know this can be done easily with List instead of Dictionary but I don't want to.

Thanks

like image 324
JavaSa Avatar asked Dec 21 '12 22:12

JavaSa


People also ask

Does forEach run in order?

forEach() , and it will definitely iterate over array elements in ascending index order (skipping indices that were never assigned a value).

How do you iterate the dictionary in order?

A standard solution to iterate over a dictionary in sorted order of keys is using the dict. items() with sorted() function. To iterate in reverse order of keys, you can specify the reverse argument of the sorted() function as True .

How do you use forEach in a dictionary?

Using foreach Loop We can loop through all KeyValuePair<K,V> in the dictionary and print the corresponding Key and Value from each pair. We can also iterate over the collection of keys and fetch the value using the Item[TKey] property.

Is dictionary ordered in C#?

OrderedDictionary Class represents a collection of key/value pairs that are accessible by the key or index. It is present in System.


2 Answers

Normal Dictionary does not guarantee order of items.

You need OrderedDictionary if you want to maintain order items where added to it. Note that there is no generic version of this class in .Net framework, so either have to give up some type-safety or find other implementation (i.e. https://www.codeproject.com/Articles/18615/OrderedDictionary-T-A-generic-implementation-of-IO as suggested by Tim S).

Alternatively if O(log n) lookup is fine and keys should be sorted - SortedDictionary.

like image 191
Alexei Levenkov Avatar answered Oct 18 '22 21:10

Alexei Levenkov


Sounds like what you want is a Queue<T>: http://msdn.microsoft.com/en-us/library/7977ey2c.aspx

Add your KeyValuePair<T, U> items to it in the order you want and then foreaching over it will be in first-in/first-out order.

like image 4
mletterle Avatar answered Oct 18 '22 21:10

mletterle