Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return List with Maximum Count using Linq

Using C# and Linq how would i return the List<....> with the largest size / count?

like image 249
Faizan Kazi Avatar asked Nov 14 '10 20:11

Faizan Kazi


People also ask

How to get maximum 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 to use Count function in LINQ query?

Syntax: int Count<TSource>(); Count<TSource>(Func<TSource, bool> predicate): This method is used to return the number of items which satisfy the given condition. The return type of this method is System.

How to find max value in List c#?

The standard solution to get the minimum value in a sequence of values is using the Min() method. Similarly to get the maximum value, use the Max() method.

What does Count return in c#?

In its simplest form (without any parameters), the Count() method returns an int indicating the number of elements in the source sequence. IEnumerable<string> strings = new List<string> { "first", "then", "and then", "finally" }; // Will return 4 int result = strings. Count();


1 Answers

I'm assuming that you have a collection of lists called lists and you want to return the list in this collection that has the most elements. If so, try this:

var listWithLargestCount = lists.OrderByDescending(list => list.Count()).First();

Alternatively if this is LINQ to Objects and you have a lot of lists you might want to try this to get better performance by avoiding the O(n log n) sort:

int maxCount = lists.Max(list => list.Count());
var listWithLargestCount = lists.First(list => list.Count() == maxCount);
like image 124
Mark Byers Avatar answered Oct 13 '22 23:10

Mark Byers