【问题标题】:Get dictionary key by list value通过列表值获取字典键
【发布时间】:2020-08-06 22:08:09
【问题描述】:

我将从this previous question 获得灵感。我有一本字典,里面有列表,我想通过其中一个值来获取键。

Dictionary<string, List<string>> myDict = new Dictionary<string, List<string>>
{
    {"1", new List<string>{"1a", "1b"} },
    {"2", new List<string>{"2a", "2b"} },
    {"3", new List<string>{"3a", "3b"} },
};

我相信里面的所有值都是独一无二的。

我想要这样的东西:

getByValueKey(字符串值);

getByValueKey("2a") 必须返回 "2"。

【问题讨论】:

  • 我认为您要么必须遍历所有条目才能找到它,要么使用此字典构建反向映射字典并使用它。这与您链接的问题几乎相同,除了您可以使用 .Contains("2a") not == "2a" 测试值
  • 谢谢!我想知道是否有类似于 Kimi 发布的单行解决方案:var myKey = types.FirstOrDefault(x =&gt; x.Value == "one").Key;

标签: c# dictionary unity3d


【解决方案1】:

如果你想使用 linq,你可以这样写:

var result = myDict.FirstOrDefault(p => p.Value.Contains(stringTofind)).Key;

【讨论】:

    【解决方案2】:

    我喜欢 Frenchy 的回答,但如果您正在寻找非 linqy 解决方案,那么:

    Dictionary<string, List<string>> myDict = new Dictionary<string, List<string>>
    {
        {"1", new List<string>{"1a", "1b"} },
        {"2", new List<string>{"2a", "2b"} },
        {"3", new List<string>{"3a", "3b"} },
    };
    
    string stringToFind = "2a";
    
    string matchingKey = null;
    foreach(KeyValuePair<string, List<string>> kvp in myDict)
    {
        if (kvp.Value.Contains(stringToFind))
        {
            matchingKey = kvp.Key;
            break;
        }
    }
    
    if (matchingKey != null)
    {
        System.Console.WriteLine("Matching Key: " + matchingKey);
    }
    else
    {
        System.Console.WriteLine("No match found.");
    }
    

    【讨论】:

    • 谢谢!虽然我更喜欢法式版本(简洁是我的小烦恼),但你的作品完美无缺。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2013-08-29
    • 2016-01-07
    • 2013-05-22
    • 1970-01-01
    • 2018-04-13
    • 2019-03-27
    • 2022-06-16
    相关资源
    最近更新 更多