使用LINQ将Dictionary<Guid,IList<String>>转换为Dictionary<string,IList<Guid>>?

3

我有一个Dictionary<Guid,IList<string>>,它显示了实体可能拥有的所有名称。

我想将其转换为查看所有名称映射到所有实体的方式。

[["FFF" => "a", "b"],
 ["EEE" => "a", "c"]] 

成为
[["a" => "FFF", "EEE"],
 ["b" => "FFF"],
 ["c" => "EEE"]]

我知道使用foreach很容易实现,但是我想知道是否有用LINQ/ToDictionary的方法?

3个回答

6
private static void Main(string[] args)
{
    var source = new Dictionary<Guid, IList<string>>
    {
        { Guid.NewGuid(), new List<string> { "a", "b" } },
        { Guid.NewGuid(), new List<string> { "b", "c" } },
    };

    var result = source
        .SelectMany(x => x.Value, (x, y) => new { Key = y, Value = x.Key })
        .GroupBy(x => x.Key)
        .ToDictionary(x => x.Key, x => x.Select(y => y.Value).ToList());

    foreach (var item in result)
    {
        Console.WriteLine($"Key: {item.Key}, Values: {string.Join(", ", item.Value)}");
    }
}

2
var dic = new Dictionary<string, List<string>>()
{
    {"FFF", new List<string>(){"a", "b"}},
    {"EEE", new List<string>(){"a", "c"}}
};

var res = dic.SelectMany(x => x.Value, (x,y) => new{Key = y, Value = x.Key})
             .ToLookup(x => x.Key, x => x.Value);

0
Dictionary<int,IList<string>> d = new Dictionary<int ,IList<string>>(){
{1,new string[]{"a","b"}},
{2,new string[]{"a","d"}},
{3,new string[]{"b","c"}},
{4,new string[]{"x","y"}}};

d.SelectMany(kvp => kvp.Value.Select(element => new { kvp.Key, element}))
 .GroupBy(g => g.element, g => g.Key)
 .ToDictionary(g => g.Key, g => g.ToList());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接