我有一个通用的OrderedDictionary,它是我从这个储存库上采用的,工作正常。我想添加一个扩展方法,它返回给定TKey的索引号。通用OrderedDictionary有一个IndexOf()方法的实现,但这是针对KeyValuePair的,而不是针对TKey的。
如何实现扩展方法,以返回与字典键TKey对应的整数索引号?
发布于 2015-11-24 22:52:14
试试下面的代码。注意,GenericOrderedDictionary是泛型OrderedDictionary,而不是标准.Net,因为没有泛型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;
}修改了:,如果您同时知道TKey和TValue,您也可以使用IndexOf()方法,如下所示。假设TKey和TValue分别是字符串和int,但当然可以是其他类型。
KeyValuePair<string, int> newItem = new KeyValuePair<string, int>("StringValue", 35);
int keyIndex = GenericOrderedDictionaryObject.IndexOf(newItem );
如果IndexOf()方法得到了很好的优化,因为我的第一个解决方案是基于顺序搜索的,这并不是最优的,所以我想到了这一点。
https://stackoverflow.com/questions/33905271
复制相似问题