首页 > 解决方案 > 使用 LINQ 从字典中的键获取值列表

问题描述

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

        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 实现此结果?

更新 :

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

标签: c#linqdictionary

解决方案


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

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

a 的最大优点Dictionary是使用键插入和检索值的时间复杂度是O(1); 如果您循环浏览KeyValuePair它包含的所有内容,您将完全取消使用 a 的目的,Dictionary因为它会进行检索O(n)


推荐阅读