如何通过键从 C# 中的 OrderedDictionary 获取索引?
How do I get a index from a OrderedDictionary in C# by key?
我正在向 OrderedDictionary
中插入值,并且需要一种方法来获取给定键的索引。这可能吗?
var groups = new OrderedDictionary();
groups.Add("group1", true);
...
var pos = someFunc(groups, "group1");
// do something with `pos`
这是我想出来的。
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);
}
如果你真的必须得到索引,你可以写一个扩展方法到return索引:
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;
}
用法:
var groups = new OrderedDictionary();
groups.Add("group1", true);
groups.Add("group2", true);
Console.WriteLine(groups.IndexOfKey("group2")); // 1
我正在向 OrderedDictionary
中插入值,并且需要一种方法来获取给定键的索引。这可能吗?
var groups = new OrderedDictionary();
groups.Add("group1", true);
...
var pos = someFunc(groups, "group1");
// do something with `pos`
这是我想出来的。
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);
}
如果你真的必须得到索引,你可以写一个扩展方法到return索引:
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;
}
用法:
var groups = new OrderedDictionary();
groups.Add("group1", true);
groups.Add("group2", true);
Console.WriteLine(groups.IndexOfKey("group2")); // 1