Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 806
jmasterx Avatar asked Nov 26 '25 10:11

jmasterx


1 Answers

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)}");
    }
}
like image 63
flipchart Avatar answered Nov 27 '25 23:11

flipchart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!