转动词典<guid,ilist <string>&gt; into Dictionary <string,ilist <guid>&gt;使用LINQ?

时间:2016-11-07 16:16:55

标签: c# linq dictionary

我有OnClickListener,显示实体可以拥有的所有名称。

我想转换它以查看映射到所有实体的所有名称。 这样:

Dictionary<Guid,IList<string>>

变为

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

我知道这对foreaches很容易,但是我想知道LINQ / ToDictionary是否有办法?

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分: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);

答案 2 :(得分: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());