【问题标题】:Get values list from a key in Dictionary using LINQ使用 LINQ 从字典中的键获取值列表
【发布时间】:2019-10-10 14:36:29
【问题描述】:

我编写了下面的代码来从具有给定键的字典中获取所有值。

        Dictionary<string,string> _dictionary;

        public List<string> GetValuesUsingKey(string key)
        {
            List<string> outp = new List<string>();
            foreach(var d in _dictionary)
            {
                if (d.Key == key)
                {
                    outp.Add(d.Value);
                }
            }
            return outp;
        } 

有没有更简单的方法可以使用 LINQ 实现此结果?

更新:

原来我对字典有误解,虽然我可以为一个键使用多个值但我错了

【问题讨论】:

  • 什么是_dictionary?如果确实是Dictionary&lt;string,string&gt;,则键是唯一的,这意味着每个键最多有 1 个元素。所以最有效的方法就是_dictinoary[key]
  • @René 但这可能会抛出问题,我推荐TryGetValue(string key)
  • 所以这意味着在我的情况下我应该使用类似 List> 的东西? @RenéVogt
  • 您可能想要List&lt;KeyValuePair&lt;string,string&gt;&gt; 之类的东西,但我们无法确定,因为我们不知道您要在此处存储什么样的数据。
  • 如果你的数据对同一个键有多个条目,你可以使用ILookup&lt;TKey, TElement,它可以通过调用Linq的ToLookup来创建:docs.microsoft.com/en-us/dotnet/api/…

标签: c# linq dictionary


【解决方案1】:

Dictionary 中的键保证是唯一的,因此无需返回 List

public string GetValueUsingKey(string key)
{
  bool isKeyPresent = _dictionary.TryGetValue(key, out var output);
  return isKeyPresent ? output : _YOUR_DEFAULT_BEHAVIOUR_;
}

Dictionary 的一大优点是使用键插入和检索值的时间复杂度是O(1);如果您循环浏览所有KeyValuePair 它包含您完全无效使用Dictionary 的目的,因为它会使检索O(n)

【讨论】:

    【解决方案2】:

    Dictionary 是一对一映射,给定键不能有多个值。

    ILookup 另一方面支持这种情况,以及空键:

    using System.Linq;
    
    class Element
    {
        public string Key { get; }
        public string Value { get; }
        ...
    }
    
    IEnumerable<Element> elements = ...
    ILookup<string, string> lookup = elements.ToLookup(e => e.Key, e => e.Value);
    

    然后得到你的结果:

    List<string> outp = lookup[key].ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      相关资源
      最近更新 更多