2015-11-24 24 views
1

我有一個通用OrderedDictionary,我採用從this repository和正常工作正常。我想添加一個擴展方法,該方法返回給定TKey的索引號。 Generic OrderedDictionary有一個IndexOf()方法的實現,但這是針對KeyValuePair而不是TKey的。Generic OrderedDictionary:如何獲得一個鍵的索引?

我該如何去實現一個擴展方法來返回對應於字典鍵TKey的整數索引號?

+0

整數索引對字典無效... –

+1

您是否知道['SortedDictionary '](https://msdn.microsoft.com/zh-cn/library/f7fta44c( v = vs.110)的.aspx)? –

+0

「整數索引對字典沒有意義......」再次閱讀問題。無論TKey是什麼,它都可以得到密鑰的索引。 – user2921851

回答

2

請嘗試下面的代碼。請注意,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分別是字符串和int,但當然可以是其他類型。

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

int keyIndex = GenericOrderedDictionaryObject.IndexOf(newItem);

我萬一想到這裏作爲我的第一解決方案是基於一個順序搜索這不是最佳的IndexOf()方法是公優化。

+0

謝謝。有用!不知何故,我與TKey和TValue混淆了! – user2921851

+0

源代碼中的註釋說,'dictionary.Keys'返回鍵的無序集合。 – PetSerAl

相關問題