Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerating through a Dictionary.KeyCollection in order

According to MSDN:

The order of the keys in the Dictionary.KeyCollection is unspecified

I am assuming that this is because additions to the Dictionary are placed into some sort of a hash table.

However, I would like to return the .Keys collection from a Dictionary as an IEnumerable (or perhaps as an ICollection) from a method, and enumerate through them in the order they were originally added to the Dictionary.

How best to accomplish this?

(I am using Winforms, .NET 2.0)

like image 979
Andy Avatar asked Dec 18 '10 15:12

Andy


People also ask

Can you enumerate through a dictionary Python?

Python Iterate Through Dictionary. You can iterate through a Python dictionary using the keys(), items(), and values() methods. keys() returns an iterable list of dictionary keys. items() returns the key-value pairs in a dictionary.

How do you use enumerate in a dictionary?

verb (used with object), e·nu·mer·at·ed, e·nu·mer·at·ing. to mention separately as if in counting; name one by one; specify, as in a list: Let me enumerate the many flaws in your hypothesis. to ascertain the number of; count.

How do I iterate through a dictionary key?

In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.


2 Answers

Then keep the keys separately in a List<T>. That original order no longer exists on the dictionary. The list will repeat insertion order.

like image 66
Marc Gravell Avatar answered Sep 19 '22 01:09

Marc Gravell


You could use List<KeyValuePair<K,V>> in place of Dictionary<K,V> to maintain order. The problem with this of course is that it becomes harder to update the value for a key and the fact that you can have duplicate keys. But that can be handled with these extension methods

    public static void AddOrUpdate<K, V>(this List<KeyValuePair<K, V>> list, K key, V value)
    {
        var pair = list.SingleOrDefault(kvp => kvp.Key.Equals(key));
        if (!pair.Equals(null))
            list.Remove(pair);
        list.Add(new KeyValuePair<K, V>(key, value));
    }

    public static V GetValue<K, V>(this List<KeyValuePair<K, V>> list, K key)
    {
        var pair = list.SingleOrDefault(kvp => kvp.Key.Equals(key));
        if (pair.Equals(null))
            return default(V); //or throw an exception
        return pair.Value;
    }

    public static bool ContainsKey<K, V>(this List<KeyValuePair<K, V>> list, K key)
    {
        return list.Any(kvp => kvp.Key.Equals(key));
    }
like image 45
juharr Avatar answered Sep 21 '22 01:09

juharr