Search code examples
c#.netlinqfluent

LINQ method syntax to group by a column, pick one element from each group with total count per group


I am looking for a LINQ query using the method syntax to group by a column, pick the first member of each group and add total count of each group into the selected entities of each group.

Is there a way to achieve this in a single elegant statement in LINQ method syntax?

Input:

OrderId  Name       Category
=============================
1        Sam        X
2        Sam        Y
3        Matthew    A
4        Matthew    B

Output:

OrderId  Name       Category    Count
======================================
1        Sam        X           2
4        Matthew    B           2

Something like this. The value of category is irrelevant to me, I just want to get any element from the group.


Solution

  • Should be as simple as a GroupBy with a projection and some aggregates

    var results  = someList
          .Group(x => x.Name)
          .Select(x => new Entity()
             {
                Name = x.Key,
                OrderId = x.First().OrderId,
                Category = x.First().Category,  
                Count = x.Count()
             });