字典值作为不同的键

Joh*_*son 1 c# string dictionary list

我有这个:

        var color = new Dictionary<string, List<string>>();
        color.Add("Blue", new List<string>() { "1", "2" });
        color.Add("Green", new List<string>() { "2", "3" });
        color.Add("Red", new List<string>() { "1", "3" });
        color.Add("Black", new List<string>() { "3" });
        color.Add("Yellow", new List<string>() { "1" });
Run Code Online (Sandbox Code Playgroud)

我想将此转换为

Dictionary<string, List<string>>
Run Code Online (Sandbox Code Playgroud)

看起来像这样:

Key: 1, Value: Blue, Red, Yellow
Key: 2, Value: Blue, Green
Key: 3, Value: Green, Red, Black
Run Code Online (Sandbox Code Playgroud)

尝试:

var test = color.GroupBy(x => x.Value.FirstOrDefault())
.ToDictionary(g => g.Key, g => g.Select(x => x.Key).ToList());
Run Code Online (Sandbox Code Playgroud)

但是这只适用于一个项目("FirstOrDefault()"),我只能得到

Key: 1, Value: Blue, Red, Yellow
Run Code Online (Sandbox Code Playgroud)

我怎么能这样做?我可以循环遍历值(不同)并循环键并检查值是否存在然后构建一个新的但我想避免这种情况并使用lamda.

看过很多这样的例子,但没有字符串列表作为值,只有一个字符串.

kan*_*152 6

试试这个:

var test = color
    .SelectMany(x => x.Value.Select(v =>
    new
    {
       Color = x.Key,
       Integer = v
    }))
    .GroupBy(x => x.Integer)
    .ToDictionary(x => x.Key, x => x.Select(y => y.Color).ToList());
Run Code Online (Sandbox Code Playgroud)