6

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

Faizan Kazi
  • 545
  • 1
  • 10
  • 18

3 Answers3

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
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
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