user1784622
user1784622

Reputation: 639

how to find which value has the maximum number of rows in a table using LinQ?

Have a look at the below table:

student       Subject
badhon        English
jack          math
andy          physics
farhan        english
joe           english
foe           physics

Now I need to know which subject has the maximum entry & what the number is? I know its simple for experienced guys, but I'm really new to LinQ. So if you can give me any reference to study various LinQ Example, that would be too great. Thanks.

Upvotes: 0

Views: 79

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1504182

Well, it looks like you want to group by rows, then order them by count (descending) and take the first result:

var subjectsByCount = rows.GroupBy(row => row.Subject)
                          .Select(g => new { Subject = g.Key, Count = g.Count() })
                          .OrderByDescending(x => x.Count);
var biggestSubject = subjectsByCount.First();

// Now you can use biggestSubject.Subject and biggestSubject.Count

Strictly speaking, the ordering is unnecessary - with something like MaxBy in MoreLINQ you could find the maximum without sorting the whole thing. But this is the simplest way if you just want to stay within vanilla LINQ.

Upvotes: 2

Related Questions