使用 Linq 返回具有最大计数的列表

发布于 2024-10-02 05:46:24 字数 48 浏览 1 评论 0原文

使用 C# 和 Linq 我将如何返回列表<....>最大尺寸/数量?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

安静 2024-10-09 05:46:24

我假设您有一个名为 lists 的列表集合,并且您希望返回该集合中元素最多的列表。如果是这样,请尝试以下操作:

var listWithLargestCount = lists.OrderByDescending(list => list.Count()).First();

或者,如果这是 LINQ to Objects 并且您有很多列表,您可能希望尝试此操作,通过避免 O(n log n) 排序来获得更好的性能:

int maxCount = lists.Max(list => list.Count());
var listWithLargestCount = lists.First(list => list.Count() == maxCount);

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);
终止放荡 2024-10-09 05:46:24

听起来好像您有 n 个列表,并且您希望挑选出数量最多的一个。

试试这个:

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

您现在拥有元素数量最多的列表。考虑这样的场景:有 2 个以上的列表具有相同的顶部元素数。

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.

爱已欠费 2024-10-09 05:46:24
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);
}

替换 i => i 具有定义“最大尺寸/计数”的函数。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文