【发布时间】:2011-01-14 20:32:38
【问题描述】:
如何通过索引从 OrderedDictionary 中获取 item 的 key 和 value?
【问题讨论】:
-
考虑更改接受的答案。
标签: c# ordereddictionary
如何通过索引从 OrderedDictionary 中获取 item 的 key 和 value?
【问题讨论】:
标签: c# ordereddictionary
没有直接的内置方法可以做到这一点。这是因为对于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 的访问。
【讨论】:
OrderedDictionary中必然是不同的结构。
orderedDictionary.Cast<DictionaryEntry>().ElementAt(index);
【讨论】:
using System.Linq;
orderedDictionary.Cast<DictionaryEntry>().ElementAt(index).Key.ToString();
我使用前面提到的代码创建了一些通过索引获取键和键值的扩展方法。
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);
}
}
【讨论】: