如何使用LINQ获取int数组中的前3个元素?

Amr*_*rhy 13 c# linq .net-3.5

我有以下整数数组:

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)

  • QuickWatch可能很保守,试图不为你执行代码,除非你真的要求它.查询实际上没有数据 - 它只知道如何获取数据.获取数据可能很慢,或者可能有副作用,因此默认情况下在调试器中显示数据是个坏主意. (2认同)

CMS*_*CMS 13

您的代码对我来说似乎很好,您可能希望将结果返回到另一个数组?

int[] topThree = array.OrderByDescending(i=> i)
                      .Take(3)
                      .ToArray();
Run Code Online (Sandbox Code Playgroud)