Using C# and Linq how would i return the List<....> with the largest size / count?
Asked
Active
Viewed 1.1k times
3 Answers
14
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);

Mark Byers
- 811,555
- 193
- 1,581
- 1,452
-
thanks Mark! I like your solution. thanks for factoring in sort time :) that'll be very useful... – Faizan Kazi Nov 15 '10 at 08:02
7
It sounds as if you have n Lists, and you wish to single out the one with the largest count.
Try this:
List<int> ints1 = new List<int> { 10, 20, 30 };
List<int> ints2 = new List<int> { 1, 2, 3, 4 };
List<int> ints3 = new List<int> { 100, 200 };
var listWithMost = (new List<List<int>> { ints1, ints2, ints3 })
.OrderByDescending(x => x.Count())
.Take(1);
You now have the List with the most number of elements. Consider the scenario where there are 2+ lists with the same top number of elements.

p.campbell
- 98,673
- 67
- 256
- 322
-
-
3It's probably better to use `.First()` than `.Take(1)`, because then you will actually get the list back instead of a list with one element containing the list. – recursive Nov 16 '10 at 19:07
1
int[] numbers = new int[] { 1, 54, 3, 4, 8, 7, 6 };
var largest = numbers.OrderByDescending(i => i).Take(4).ToList();
foreach (var i in largest)
{
Console.WriteLine(i);
}
replace i => i
with a function defining "largest size / count".

Albin Sunnanbo
- 46,430
- 8
- 69
- 108