如何在C#中通过索引从OrderedDictionary获取键?

24

如何通过索引从有序字典(OrderedDictionary)获取项目的键(key)和值(value)?


请考虑更改已接受的答案。 - Peter Mortensen
3个回答

51
orderedDictionary.Cast<DictionaryEntry>().ElementAt(index);

2
使用 using System.Linq; - testing
使用这段代码可以获取元素。但是我如何像SO问题中那样获取键和值呢? - testing
8
orderedDictionary.Cast<DictionaryEntry>().ElementAt(index).Key.ToString(); - testing
3
实际上,这应该成为被接受的答案。在这里验证 - https://referencesource.microsoft.com/#System/compmod/system/collections/specialized/ordereddictionary.cs,210 - Angshuman Agarwal

8

没有直接内置的方法来实现这一点。这是因为对于一个 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 list = 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; } } - Red Swan
@RedSwan:索引在哪里? - testing
5
索引绝对不是关键字 - 在“OrderedDictionary”中,它们是必然不同的构造。 - Conrad
2
因为索引不是关键字,所以被downvote了,正如@martin-r-l的答案所示。 - Justin

2

我创建了一些扩展方法,使用之前提到的代码通过索引获取键和通过键获取值。

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);
    }
}

3
如果你的意图是在目标索引/键不在所选字典中时返回默认值,那么你选择了一种昂贵的方式。相对于if/else这样的正常控制流结构,异常非常昂贵。最好自己检查越界索引和不存在的键,而不是依赖于异常发生。 - Odrade

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接