我有以下整数数组:
int[] array = new int[7] { 1, 3, 5, 2, 8, 6, 4 };
Run Code Online (Sandbox Code Playgroud)
我编写了以下代码来获取数组中的前3个元素:
var topThree = (from i in array orderby i descending select i).Take(3);
Run Code Online (Sandbox Code Playgroud)
当我查看里面的内容时topThree
,我发现:
{System.Linq.Enumerable.TakeIterator}
count:0
我做错了什么以及如何更正我的代码?
Jon*_*eet 26
你是怎么"检查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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
看起来对我好......
找到前N个值的方法可能比排序更有效,但这肯定有效.您可能要考虑对只执行一项操作的查询使用点表示法:
var topThree = array.OrderByDescending(i => i)
.Take(3);
Run Code Online (Sandbox Code Playgroud)
CMS*_*CMS 13
您的代码对我来说似乎很好,您可能希望将结果返回到另一个数组?
int[] topThree = array.OrderByDescending(i=> i)
.Take(3)
.ToArray();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
25762 次 |
最近记录: |