Reputation: 4197
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"},
};
I want to group them into a list of lists by the multiple properties, in this example by Id
and Name
.
This would split the original list into the following (where the number represents PersonId
):
{[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?
Upvotes: 2
Views: 7117
Reputation: 21764
Just do:
List<List<Campaign>> groups = cmps.GroupBy(c => new { c.Id, c.Name })
.Select(group => group.ToList())
.ToList();
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.
Upvotes: 9