Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linq

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/11/10 1-2
7 10/12/10 5-6

I just want to list the Maximun of rows per date by range, like this:

Date  Range  Total
10/10/10 9-10  3
10/11/10 1-2  2
10/12/10 5-6  1

I want to do this by using LINQ, do you have any ideas of how to do this?

like image 266
cvsr1980 Avatar asked Nov 16 '10 23:11

cvsr1980


People also ask

How to get the max value in LINQ?

In LINQ, you can find the maximum element of the given sequence by using Max() function. This method provides the maximum element of the given set of values.

How do you count in LINQ?

In LINQ, you can count the total number of elements present in the given sequence by using the Count Method. This method returns the total number of elements present in the given sequence.

What is the advantage of LINQ in C#?

The primary reason that LINQ was introduced with C# 3.0 was to reduce the amount of coding that object retrieval required, in comparison to more traditional for each loops, and it is largely due to this reason that LINQ has gained such popularity within the field.


2 Answers

I think something along these lines should work:

List<MyTable> items = GetItems();
var orderedByMax = from i in items
                   group i by i.Date into g
                   let q = g.GroupBy(i => i.Range)
                            .Select(g2 => new {Range = g2.Key, Count = g2.Count()})
                            .OrderByDescending(i => i.Count)
                   let max = q.FirstOrDefault()
                   select new {
                      Date = g.Key,
                      Range = max.Range,
                      Total = max.Count
                   };
like image 117
StriplingWarrior Avatar answered Sep 22 '22 07:09

StriplingWarrior


Using extension methods:

List<MyTable> 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
like image 23
Jla Avatar answered Sep 25 '22 07:09

Jla