How do I get a key from a OrderedDictionary in C# by index?
orderedDictionary.Cast<DictionaryEntry>().ElementAt(index);
There is not a direct built-in way to do this. This is because for an OrderedDictionary
the index is the key; if you want the actual key then you need to track it yourself. Probably the most straightforward way is to copy the keys to an indexable collection:
// dict is OrderedDictionary
object[] keys = new object[dict.Keys.Count];
dict.Keys.CopyTo(keys, 0);
for(int i = 0; i < dict.Keys.Count; i++) {
Console.WriteLine(
"Index = {0}, Key = {1}, Value = {2}",
i,
keys[i],
dict[i]
);
}
You could encapsulate this behavior into a new class that wraps access to the OrderedDictionary
.
I created some extension methods that get the key by index and the value by key using the code mentioned earlier.
public static T GetKey<T>(this OrderedDictionary dictionary, int index)
{
if (dictionary == null)
{
return default(T);
}
try
{
return (T)dictionary.Cast<DictionaryEntry>().ElementAt(index).Key;
}
catch (Exception)
{
return default(T);
}
}
public static U GetValue<T, U>(this OrderedDictionary dictionary, T key)
{
if (dictionary == null)
{
return default(U);
}
try
{
return (U)dictionary.Cast<DictionaryEntry>().AsQueryable().Single(kvp => ((T)kvp.Key).Equals(key)).Value;
}
catch (Exception)
{
return default(U);
}
}