从具有公用值的字典中获取TKey,其中TValue为List <string>

Wat*_*rap 2 c# dictionary

我有一本字典,看起来像这样:

Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>()
{
    {"a" , new List<string> { "Red","Yellow"} },
    {"b" , new List<string> { "Blue","Red"} },
    {"c" , new List<string> { "Green","Orange"} },
    {"d" , new List<string> { "Black","Green"} },
};
Run Code Online (Sandbox Code Playgroud)

我需要从dict其中的通用值List<string>应该是键,值应该是键的列表的字典输出。

例如:

Red: [a,b]
Green: [c,d]
Run Code Online (Sandbox Code Playgroud)

我不知道如何使用listin dictionaryas 解决此问题TValue

请向我解释如何在字典中处理列表。

Ale*_*eev 5

您可以使用来修饰您的字典SelectMany并获得看起来像的普通列表

"a" - "Red"
"a" - "Yellow"
"b" - "Blue"
"b" = "Red"
// and so on
Run Code Online (Sandbox Code Playgroud)

然后按值分组并从这些分组中构建新的字典。试试这个代码:

var commonValues = dict.SelectMany(kv => kv.Value.Select(v => new {key = kv.Key, value = v}))
    .GroupBy(x => x.value)
    .Where(g => g.Count() > 1)
    .ToDictionary(g => g.Key, g => g.Select(x => x.key).ToList());
Run Code Online (Sandbox Code Playgroud)