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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2229951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:34:42  来源:igfitidea点击:

How do I get a key from a OrderedDictionary in C# by index?

c#ordereddictionary

提问by Red Swan

How do I get the key and value of item from OrderedDictionary by index?

如何通过索引从 OrderedDictionary 中获取 item 的键和值?

采纳答案by jason

There is not a direct built-in way to do this. This is because for an OrderedDictionarythe index isthe key; if you want the actual key then you need to track it yourself. Probably the most straightforward way is to copy the keys to an indexable collection:

没有直接的内置方法可以做到这一点。这是因为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]
    );
}

You could encapsulate this behavior into a new class that wraps access to the OrderedDictionary.

您可以将此行为封装到一个新类中,该类包含对OrderedDictionary.

回答by Martin R-L

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

回答by Halcyon

I created some extension methods that get the key by index and the value by key using the code mentioned earlier.

我创建了一些扩展方法,它们使用前面提到的代码按索引获取键和按键获取值。

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