【问题标题】:Get Key From String Where Value Is List<string>从值为 List<string> 的字符串中获取键
【发布时间】:2014-01-24 03:35:05
【问题描述】:

我有一个字典,其中键是字符串,值是字符串列表。

Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>() {
    {"alpha", new List<string> {"one", "two", "three"}}
    {"beta", new List<string> {"four", "five", "six"}}
    {"gamma", new List<string> {"seven", "eight", "nine"}}
}

当给定值中存在的字符串时,有没有办法返回键?

例如,给定"four",返回"beta"

我找到了类似this 的东西,但它仅在值为单个而不是列表时才有效,而且我不知道如何使用列表来做到这一点。

谢谢。

【问题讨论】:

    标签: c# list dictionary key


    【解决方案1】:

    但是,按值搜索字典效率不高:

    string firstKey = dict.Where(kv => kv.Value.Contains("four"))
        .Select(kv => kv.Key)
        .FirstOrDefault(); // returns null if no list contains "four"
    

    或者如果没有列表包含给定值,您可以提供默认键,那么使用First 是安全的:

    string firstKey = dict.Where(kv => kv.Value.Contains("foo"))
        .Select(kv => kv.Key)
        .DefaultIfEmpty("--no value found--")
        .First(); // result: "--no value found--"
    

    【讨论】:

      【解决方案2】:

      这里的问题是任何给定的字符串值都可能有多个键。因此,您需要返回一个集合而不是单个键。这可以按如下方式完成

      IEnumerable<string> FindAllKeys(Dictionary<string, List<string>> map, string value) {
        foreach (var pair in map) {
          if (pair.Value.IndexOf(value) >= 0) {
            yield return pair.Key;
          }
        }
      }
      

      如果您想在第一次匹配时关闭此搜索,您可以使用 FirstOrDefault 扩展方法

      FindAllKeys(dict, "four").FirstOrDefault();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多