开发者

Return List with Maximum Count using Linq

Using 开发者_开发知识库C# and Linq how would i return the List<....> with the largest size / 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);


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜