How to get the Max() of a Count() with LINQ

前端 未结 4 919
面向向阳花
面向向阳花 2021-02-08 20:45

I\'m new to LINQ and I have this situation. I have this table:

ID Date  Range
1 10/10/10 9-10
2 10/10/10 9-10
3 10/10/10 9-10
4 10/10/10 8-9
5 10/11/10 1-2
6 10/         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-08 21:23

    Using extension methods:

    List items = GetItems();
    
    var rangeTotals = items.GroupBy(x => new { x.Date, x.Range }) // Group by Date + Range
                      .Select(g => new { 
                                  Date = g.Key.Date, 
                                  Range = g.Key.Range, 
                                  Total = g.Count() // Count total of identical ranges per date
                                  });
    
    var rangeMaxTotals = rangeTotals.Where(rt => !rangeTotals.Any(z => z.Date == rt.Date && z.Total > rt.Total)); // Get maximum totals for each date
    

提交回复
热议问题