C# 如何使用 LINQ 获取 int 数组中的前 3 个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1169759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the top 3 elements in an int array using LINQ?
提问by Amr Elgarhy
I have the following array of integers:
我有以下整数数组:
int[] array = new int[7] { 1, 3, 5, 2, 8, 6, 4 };
I wrote the following code to get the top 3 elements in the array:
我编写了以下代码来获取数组中的前 3 个元素:
var topThree = (from i in array orderby i descending select i).Take(3);
When I check what's inside the topThree
, I find:
当我检查里面的内容时topThree
,我发现:
{System.Linq.Enumerable.TakeIterator}
count:0
{System.Linq.Enumerable.TakeIterator}
计数:0
What did I do wrong and how can I correct my code?
我做错了什么,如何更正我的代码?
采纳答案by Jon Skeet
How did you "check what's inside the topThree"? The easiest way to do so is to print them out:
你是如何“检查topThree里面的东西”的?最简单的方法是将它们打印出来:
using System;
using System.Linq;
public class Test
{
static void Main()
{
int[] array = new int[7] { 1, 3, 5, 2, 8, 6, 4 };
var topThree = (from i in array
orderby i descending
select i).Take(3);
foreach (var x in topThree)
{
Console.WriteLine(x);
}
}
}
Looks okay to me...
对我来说看起来没问题...
There are potentially more efficient ways of finding the top N values than sorting, but this will certainly work. You might want to consider using dot notation for a query which only does one thing:
有可能比排序更有效的方法来找到前 N 个值,但这肯定会奏效。您可能需要考虑对只执行一件事的查询使用点表示法:
var topThree = array.OrderByDescending(i => i)
.Take(3);
回答by CMS
Your code seems fine to me, you maybe want to get the result back to another array?
您的代码对我来说似乎很好,您可能想将结果返回到另一个数组?
int[] topThree = array.OrderByDescending(i=> i)
.Take(3)
.ToArray();
回答by jonot
Its due to the delayed execution of the linq query.
这是由于 linq 查询的延迟执行造成的。
As suggested if you add .ToArray() or .ToList() or similar you will get the correct result.
根据建议,如果您添加 .ToArray() 或 .ToList() 或类似内容,您将获得正确的结果。
回答by Saon Mukherjee
int[] intArray = new int[7] { 1, 3, 5, 2, 8, 6, 4 };
int ind=0;
var listTop3 = intArray.OrderByDescending(a=>a).Select(itm => new {
count = ++ind, value = itm
}).Where(itm => itm.count < 4);