【问题标题】:How do I get a key from a OrderedDictionary in C# by index?如何通过索引从 C# 中的 OrderedDictionary 中获取键?
【发布时间】:2011-01-14 20:32:38
【问题描述】:

如何通过索引从 OrderedDictionary 中获取 item 的 key 和 value?

【问题讨论】:

  • 考虑更改接受的答案。

标签: c# ordereddictionary


【解决方案1】:

没有直接的内置方法可以做到这一点。这是因为对于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 list = OrderItems;对象 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; } }
  • @RedSwan:索引在哪里?
  • 索引绝对是不是的关键——它们在OrderedDictionary中必然是不同的结构。
  • 被否决,因为索引不是关键,正如@martin-r-l 的答案所示
【解决方案2】:
orderedDictionary.Cast<DictionaryEntry>().ElementAt(index);

【讨论】:

  • 使用using System.Linq;
  • 使用此代码,您可以获得元素。但是如何获得 SO 问题中的键和值?
  • orderedDictionary.Cast&lt;DictionaryEntry&gt;().ElementAt(index).Key.ToString();
  • + 1 这实际上应该是公认的答案。在此处验证 - referencesource.microsoft.com/#System/compmod/system/…
【解决方案3】:

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

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

【讨论】:

  • 如果您的意图是在目标索引/键不在字典中的情况下返回默认值,那么您选择了一种昂贵的方式来做到这一点。相对于 if/else 等正常的控制流结构,异常是非常昂贵的。自己检查越界索引和不存在的键比依赖发生的异常要好得多。
猜你喜欢
  • 2015-05-12
  • 1970-01-01
  • 2016-10-28
  • 1970-01-01
  • 2011-04-27
  • 2013-02-01
  • 2018-02-16
  • 1970-01-01
  • 2018-01-06
相关资源
最近更新 更多