如何通過索引從OrderedDictionary中獲取項的鍵和值?如何通過索引從C#中的OrderedDictionary獲取密鑰?
18
A
回答
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
一個新的類。
35
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
相關問題
- 1. Java HashMap:如何通過索引獲取密鑰和值?
- 2. 如何通過索引訪問密鑰?
- 3. Java - 獲取HashMap中的密鑰索引?
- 4. 通過密鑰獲取Cookie?
- 5. PHP - 通過索引而不是密鑰獲取數組值
- 6. 如何通過一個密鑰字段從Map中獲取值?
- 7. 如何通過密鑰從RouteTable.Routes集合中獲取url?
- 8. 獲取密鑰的LinkedHashMap索引
- 9. 如何在PHP中獲取密鑰的索引號?
- 10. 如何通過c#中的索引獲取堆棧項?
- 11. 如何從密鑰中的公鑰獲取密碼
- 12. 如何通過值進行搜索並獲取多維數組中的密鑰?
- 13. 如何通過SL api獲取加密密鑰?
- 14. 從OrderedDictionary獲取名稱值
- 15. 如何通過提供密鑰名稱來獲取密鑰的特定值?
- 16. 如何通過node.js中的密鑰直接從數組中獲取值
- 17. 通過Firebase獲取密鑰元素
- 18. 通過密鑰獲取GAE實體
- 19. Reducer通過sys.stdin獲取多個密鑰?
- 20. 從Multiindex中獲取密鑰?
- 21. 如何通過CryptoAPI中的證書公鑰獲取密鑰容器的信息?
- 22. C#獲取OrderedDictionary中對象索引的最佳方式是什麼?
- 23. Openpyxl如何通過索引從工作表中獲取行
- 24. 如何通過索引從字符串中獲取char?
- 25. Java:從編碼密鑰獲取密鑰
- 26. 通過密鑰從字典中獲取單個值
- 27. 如何通過API密鑰
- 28. 如何通過API密鑰
- 29. 如何通過密鑰獲取mongo集合的孩子?
- 30. 是否可以通過前綴獲取/搜索Memcached密鑰?
我也一樣,但再次看到: 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
@RedSwan:在哪裏指數? – testing 2014-09-12 10:10:03
該索引絕對*不是鍵 - 這些在OrderedDictionary中必然是不同的結構。 – Conrad 2015-02-26 19:14:23