Home > OS >  How do I get a index from a OrderedDictionary in C# by key?
How do I get a index from a OrderedDictionary in C# by key?

Time:05-12

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`

CodePudding user response:

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

CodePudding user response:

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); 
}
  • Related