我有一个这样的对象列表:
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"},
};
我想通过多个属性将它们分组到列表列表中,在本示例中为Id
和Name
。
这会将原始列表拆分为以下列表(其中数字表示PersonId
):
{[1, 2], [3], [4, 5], [6]}
我通过编写以下代码解决了这个问题:
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();
这个解决方案似乎工作正常,但出于好奇,有没有更好/更好的方法来做到这一点?