I have a Generic OrderedDictionary which I adopted from this repository and works fine as expected. I wanted to add an extension method that returns an index number of a given TKey. The Generic OrderedDictionary has an implementation of IndexOf() method but this is for KeyValuePair rather than for a TKey.
How do I go about implementing an extension method for returning an integer index number corresponding to a dictionary key TKey?
Try the following code. Note that GenericOrderedDictionary is the Generic OrderedDictionary not the standard .Net as there is no Generic OrderedDictionary.
public static int IndexOfKey<TKey, TValue>(this GenericOrderedDictionary<TKey, TValue> dictionary, TKey key)
{
int index = -1;
foreach (TKey k in dictionary.Keys)
{
index++;
if (k.Equals(key))
return index;
}
return -1;
}
Amended: If you know both TKey and TValue, you may be able to use the IndexOf() method as well, like below. Assume TKey and TValue are string and int respectively, but of course can be other types.
KeyValuePair<string, int> newItem = new KeyValuePair<string, int>("StringValue", 35);
int keyIndex = GenericOrderedDictionaryObject.IndexOf(newItem );
I thought of this just in case IndexOf() method is well optimized as my first solution is based on a sequential search which is not optimal.
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