使用linq在c#中对键值字典列表进行分组

时间:2016-10-21 13:29:00

标签: c# .net linq

我有以下List<Dictionary<string, string>>密钥对:

enter image description here

我如何编写Linq查询,以便我只有1个字典,其中值按键分组?

2 个答案:

答案 0 :(得分:3)

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

对于给定的输入:

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

结果是:

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

答案 1 :(得分:2)

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());

输出: Name:"one,"two", Age:"22","88"