Josh L Josh L - 1 month ago 8
C# Question

Grouping a List of Key Value Dictionaries in c# using linq

I have the following

List<Dictionary<string, string>>
Key pairs:

enter image description here

How would I write my Linq query so that I have only 1 Dictionary where the Values are grouped by key?

Answer
List<Dictionary<string, string>> data = new List<Dictionary<string, string>>
{
    new Dictionary<string, string>
    {
        ["Category"] = "99",
        ["Role"] = "11",
        ["Level"] = "22",
        ["BillaleDays"] = "33",
    },
    new Dictionary<string, string>
    {
        ["Category"] = "55",
        ["Role"] = "66",
        ["Level"] = "77",
        ["BillaleDays"] = "88",
    }
};

var result = data.SelectMany(item => item)
    .GroupBy(item => item.Key)
    .ToDictionary(key => key.Key, value => value.Select(i => i.Value).ToList());

// Result:
//     Category : (99,55)
//     Role : (11,66)
//     Level : (22,77)
//     BillableDays : (33,88)