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
forEach() , and it will definitely iterate over array elements in ascending index order (skipping indices that were never assigned a value).
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 .
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.
OrderedDictionary Class represents a collection of key/value pairs that are accessible by the key or index. It is present in System.
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.
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 foreach
ing over it will be in first-in/first-out order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With