jmasterx jmasterx - 1 month ago 17
C# Question

Turning a Dictionary<Guid,IList<String>> into Dictionary<string,IList<Guid>> With LINQ?

I have a

Dictionary<Guid,IList<string>>
which shows all the names an entity can have.

I want to convert this to see all the names mapped to all the entities.
so:

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


Becomes

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


I know this is easy to do with foreaches but I'm wondering if there is a way with LINQ / ToDictionary?

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