简体   繁体   English

通过列表值获取字典键

[英]Get dictionary key by list value

I'll take inspiration from this previous question .我将从上一个问题中获得灵感。 I have a dictionary with lists inside, and I want to get the key by a value inside one of those.我有一个里面有列表的字典,我想通过其中一个值来获取键。

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"} },
};

I'm confident that all values inside are unique.我相信里面的所有价值观都是独一无二的。

I want something like this:我想要这样的东西:

getByValueKey(string value); getByValueKey(字符串值);

getByValueKey("2a") must be return "2". getByValueKey("2a") 必须返回“2”。

if you want to use linq, you could write:如果你想使用 linq,你可以写:

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

I like Frenchy's answer, but if you're looking for a non-linqy solution, then:我喜欢 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.");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM