如何通过索引从有序字典(OrderedDictionary)获取项目的键(key)和值(value)?
如何通过索引从有序字典(OrderedDictionary)获取项目的键(key)和值(value)?
orderedDictionary.Cast<DictionaryEntry>().ElementAt(index);
using System.Linq;
- testingorderedDictionary.Cast<DictionaryEntry>().ElementAt(index).Key.ToString();
- testing没有直接内置的方法来实现这一点。这是因为对于一个 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
的访问。我创建了一些扩展方法,使用之前提到的代码通过索引获取键和通过键获取值。
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);
}
}