Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic OrderedDictionary: How to get an index of a key?

Tags:

c#

generics

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?

like image 897
user2921851 Avatar asked Oct 23 '25 15:10

user2921851


1 Answers

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.

like image 128
user5525674 Avatar answered Oct 26 '25 06:10

user5525674



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!