2010-02-09 56 views

回答

10

沒有直接內置的方式做到這一點。這是因爲一個OrderedDictionary指數的關鍵;如果你想要真正的鑰匙,那麼你需要自己追蹤它。也許最簡單的方法是將密鑰複製到可轉位集合:

// dict is OrderedDictionary 
object[] keys = new object[dict.Keys.Count]; 
dict.Keys.CopyTo(keys, 0); 
for(int i = 0; i < dict.Keys.Count; i++) { 
    Console.WriteLine(
     "Index = {0}, Key = {1}, Value = {2}", 
     i, 
     keys[i], 
     dict[i] 
    ); 
} 

您可以封裝這種行爲成包接入OrderedDictionary一個新的類。

+1

我也一樣,但再次看到: OrderedDictionary列表=的OrderItems; object strKey = list [e.OldIndex]; DictionaryEntry dicEntry = new DictionaryEntry(); foreach(DictionaryEntry DE in list) if(DE.Value == strKey) { dicEntry.Key = DE.Key; dicEntry.Value = DE.Value; }} – 2010-02-10 04:47:16

+0

@RedSwan:在哪裏指數? – testing 2014-09-12 10:10:03

+2

該索引絕對*不是鍵 - 這些在OrderedDictionary中必然是不同的結構。 – Conrad 2015-02-26 19:14:23

35
orderedDictionary.Cast<DictionaryEntry>().ElementAt(index); 
+1

你先生的回答應該得到更多upvotes – Seb 2014-09-10 15:12:47

+1

使用'使用System.Linq的;' – testing 2014-09-12 09:56:54

+0

有了這個代碼,你得到的元素。但是,如何在SO問題中獲得關鍵和價值? – testing 2014-09-12 10:02:20

1

我創建了一些擴展方法,它們使用前面提到的代碼通過索引和鍵值獲取。

public static T GetKey<T>(this OrderedDictionary dictionary, int index) 
{ 
    if (dictionary == null) 
    { 
     return default(T); 
    } 

    try 
    { 
     return (T)dictionary.Cast<DictionaryEntry>().ElementAt(index).Key; 
    } 
    catch (Exception) 
    { 
     return default(T); 
    } 
} 

public static U GetValue<T, U>(this OrderedDictionary dictionary, T key) 
{ 
    if (dictionary == null) 
    { 
     return default(U); 
    } 

    try 
    { 
     return (U)dictionary.Cast<DictionaryEntry>().AsQueryable().Single(kvp => ((T)kvp.Key).Equals(key)).Value; 
    } 
    catch (Exception) 
    { 
     return default(U); 
    } 
} 
+0

如果你的目的是要恢復默認值,如果目標指數/關鍵不在詞典中,你選擇了一個昂貴的方式做到這一點。相對於像if/else這樣的正常控制流構造,異常是非常昂貴的。最好是自己檢查越界指數和不存在的密鑰,而不是依賴發生的異常。 – Odrade 2015-07-02 21:15:15

相關問題