'How do I get a index from a OrderedDictionary in C# by key?

I'm inserting values into an OrderedDictionary and need a way to obtain the index for a given key. Is this possible?

var groups = new OrderedDictionary();
groups.Add("group1", true); 
...
var pos = someFunc(groups, "group1");
// do something with `pos`


Solution 1:[1]

If you really have to get the index, you could write an extension method to return the index:

public static int IndexOfKey(this OrderedDictionary dictionary, object keyToFind)
{
    int currentIndex = 0;
    foreach (var currentKey in dictionary.Keys)
    {
        if (currentKey.Equals(keyToFind)) return currentIndex;
        currentIndex++;
    }

    return -1;
}

Usage:

var groups = new OrderedDictionary();
groups.Add("group1", true);
groups.Add("group2", true);

Console.WriteLine(groups.IndexOfKey("group2")); // 1

Solution 2:[2]

This is what I came up with.

var groups = new OrderedDictionary();
var group = "group1";

if (groups.Contains(group))
{
    var pos = groups[group];
} else
{
    var values = new int[groups.Count];
    groups.Values.CopyTo(values, 0);
    var pos = values.DefaultIfEmpty(-1).Last() + 1;
    groups.Add(group, pos); 
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 41686d6564 stands w. Palestine
Solution 2