Return List with Maximum Count using Linq

自古美人都是妖i 提交于 2019-12-21 16:26:50

问题


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


回答1:


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.




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/4179448/return-list-with-maximum-count-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!