LINQ:将对象列表按多个属性分组到列表列表的更好方法? [英] LINQ: A better way to grouping a list of objects by multiple properties in to a list of lists?

查看:135
本文介绍了LINQ:将对象列表按多个属性分组到列表列表的更好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的对象列表:

I have a list of objects as such:

var cmps = new List<Campaign>()
{
    new Campaign(){ PersonId = 1, Id = 1, Name = "Name"},
    new Campaign(){ PersonId = 2, Id = 1, Name = "Name"},
    new Campaign(){ PersonId = 3, Id = 1, Name = "Name1"},                
    new Campaign(){ PersonId = 4, Id = 2, Name = "Name1"},                
    new Campaign(){ PersonId = 5, Id = 2, Name = "Name1"},
    new Campaign(){ PersonId = 6, Id = 3, Name = "Name"},
};

我想通过多个属性将它们分组为列表列表,在此示例中,按IdName.

I want to group them into a list of lists by the multiple properties, in this example by Id and Name.

这会将原始列表拆分为以下内容(其中数字表示PersonId):

This would split the original list into the following (where the number represents PersonId):

{[1,2],[3],[4,5],[6]}

{[1, 2], [3], [4, 5], [6]}

我已经通过编写以下代码解决了这个问题:

I have solved this by writing the following code:

List<List<Campaign>> groups = cmps.GroupBy(c => new { c.Id, c.Name })
                                  .Select(c => c.Key)
                                  .ToList()
                                  .Select(v => cmps.Where(c => c.Id == v.Id && c.Name == v.Name).ToList())
                                  .ToList();

此解决方案似乎运行良好,但出于好奇,是否有更好/更好的方法来做到这一点?

This solution seems to be working fine, but out of curiosity, is there a nicer/better way to do this?

推荐答案

只需:

List<List<Campaign>> groups = cmps.GroupBy(c => new { c.Id, c.Name })
    .Select(group => group.ToList())
    .ToList();

IEnumerable上的

GroupBy返回IEnumerable<IGrouping<TKey, T>>. IGrouping<TKey, T>实现了IEnumerable<T>,因此您可以直接将组用作序列.

GroupBy on IEnumerable returns IEnumerable<IGrouping<TKey, T>>. IGrouping<TKey, T> implements IEnumerable<T>, so you can just use the group directly as a sequence.

这篇关于LINQ:将对象列表按多个属性分组到列表列表的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆