Faizan Kazi
Faizan Kazi

Reputation: 555

Return List with Maximum Count using Linq

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

Upvotes: 6

Views: 11120

Answers (3)

p.campbell
p.campbell

Reputation: 100567

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.

Upvotes: 7

Mark Byers
Mark Byers

Reputation: 838156

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

Upvotes: 14

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

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

Upvotes: 1

Related Questions