小编Joh*_*son的帖子

字典值作为不同的键

我有这个:

        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: …
Run Code Online (Sandbox Code Playgroud)

c# string dictionary list

1
推荐指数
1
解决办法
65
查看次数

标签 统计

c# ×1

dictionary ×1

list ×1

string ×1