简体   繁体   中英

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

I have the following List<Dictionary<string, string>> Key pairs:

在此处输入图片说明

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

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

For given input:

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

Result is:

Category : (99,55)
Role : (11,66)
Level : (22,77)
BillableDays : (33,88)
List<Dictionary<string, string>> data = new List<Dictionary<string,string>>
{
    new Dictionary<string, string>
    {        
        ["Name"] = "one",
        ["Age"] = "22"
    },
    new Dictionary<string, string>
    {
        ["Name"] = "two",
        ["Age"] = "88",
    }
};

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

Output: Name:"one,"two", Age:"22","88"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM