Using C# and Linq how would i return the List<....> with the largest size / count?
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.
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.
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.
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();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With