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)
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.
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.
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.
Then keep the keys separately in a List<T>
. That original order no longer exists on the dictionary. The list will repeat insertion order.
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));
}
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