繁体   English   中英

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

[英]How to get the top 3 elements in an int array using LINQ?

我有以下整数数组:

int[] array = new int[7] { 1, 3, 5, 2, 8, 6, 4 };

我编写了以下代码来获取数组中的前3个元素:

var topThree = (from i in array orderby i descending select i).Take(3);

当我检查topThree ,我发现:

{System.Linq.Enumerable.TakeIterator}
数:0

我做错了什么,我该如何纠正我的代码?

您如何“检查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);
        }
    }
}

对我来说还好...

找到最高的N个值可能比排序更有效的方法,但这肯定会起作用。 您可能要考虑对仅使用一件事的查询使用点表示法:

var topThree = array.OrderByDescending(i => i)
                    .Take(3);

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

int[] topThree = array.OrderByDescending(i=> i)
                      .Take(3)
                      .ToArray();

这是由于linq查询的执行延迟。

如建议的那样,如果添加.ToArray()或.ToList()或类似内容,您将获得正确的结果。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM