首页 > 解决方案 > 从具有常见值的字典中获取 TKey,其中 TValue 是 List

问题描述

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

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

我需要作为字典输出,dict其中的公共值List<string>应该是键,值应该是键列表。

例如:

Red: [a,b]
Green: [c,d]

我不知道如何用listin dictionaryas解决这个问题TValue

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

标签: c#dictionary

解决方案


您可以用扁平化您的字典SelectMany并获得看起来像的简单列表

"a" - "Red"
"a" - "Yellow"
"b" - "Blue"
"b" = "Red"
// and so on

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

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());

推荐阅读