简体   繁体   中英

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.

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()
         });
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM