gpt4 book ai didi

c# - 通用 OrderedDictionary : How to get an index of a key?

转载 作者:行者123 更新时间:2023-11-30 16:51:23 26 4
gpt4 key购买 nike

我有一个从 this repository 中采用的通用 OrderedDictionary并且按预期工作正常。我想添加一个扩展方法来返回给定 TKey 的索引号。 Generic OrderedDictionary 具有 IndexOf() 方法的实现,但这是针对 KeyValuePair 而不是 TKey。

我如何着手实现一个扩展方法以返回对应于字典键 TKey 的整数索引号?

最佳答案

试试下面的代码。请注意,GenericOrderedDictionary 是 Generic OrderedDictionary 而不是标准的 .Net,因为没有 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;
}

修改:如果您知道 TKey 和 TValue,您也可以使用 IndexOf() 方法,如下所示。假设TKey和TValue分别是string和int,当然也可以是其他类型。

KeyValuePair<string, int> newItem = new KeyValuePair<string, int>("StringValue", 35);

int keyIndex = GenericOrderedDictionaryObject.IndexOf(newItem );

我想到这个只是为了以防 IndexOf() 方法得到很好的优化,因为我的第一个解决方案是基于顺序搜索,这不是最优的。

关于c# - 通用 OrderedDictionary : How to get an index of a key?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33905271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com