如何通过Linq查询逐步构建组?

时间:2018-03-09 21:53:48

标签: c# linq

假设我有物品

{ // item 0
    Color = yellow,
    Priority = high,
},
{ // item 1
    Color = yellow,
    Priority = medium,
},
{ // item 2
    Color = green,
    Priority = high,
},

我希望能够逐步构建GroupBy查询,使用var grouped = items.GroupBy(item => item.Color),在这种情况下,我将拥有2个组,然后再次使用密钥item.Priority进行分组3组。

不幸的是,使用var regrouped = grouped.GroupBy(item => item.Priority)不是有效的解决方案。

最终结果必须与执行

相同
items.GroupBy(item => new {item.Color, item.Priority});

2 个答案:

答案 0 :(得分:1)

由于您要将子项重新组合为新对象,因此可以使用ToLookup创建所需的IGrouping,并SelectMany将它们展平为新的IEnumerable 1}}:

var regrouped = grouped.SelectMany(cg => cg.GroupBy(i => i.Priority)
                                           .ToLookup(pg => new { Color = cg.Key, Priority = pg.Key },
                                                     pg => pg.Select(i => i)
                                                    )
                                  );

答案 1 :(得分:0)

如果我理解正确,您希望将每个Color组分组到Priority。如果是这样的话,这应该有效:

var items = new List<Item>
{
    new Item { Color = "yellow", Priority = "high" },
    new Item { Color = "red", Priority = "high" },
    new Item { Color = "yellow", Priority = "medium" },
    new Item { Color = "red", Priority = "medium" },
    new Item { Color = "green", Priority = "high" },
    new Item { Color = "green", Priority = "high" },
    new Item { Color = "red", Priority = "high" },
};

var groupped = items.GroupBy(x => x.Color);
var regroupped = groupped.Select(x => new
{
    Color = x.Key,
    Priorities = x.GroupBy(y => y.Priority)
});

请注意,这会返回与查询相同的结果集

var regroupped = items.GroupBy(item => new {item.Color, item.Priority});