简体   繁体   English

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

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

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} {System.Linq.Enumerable.TakeIterator}
count:0 数:0

What did I do wrong and how can I correct my code? 我做错了什么,我该如何纠正我的代码?

How did you "check what's inside the topThree"? 您如何“检查topThree中的内容”? The easiest way to do so is to print them out: 最简单的方法是将它们打印出来:

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. 找到最高的N个值可能比排序更有效的方法,但这肯定会起作用。 You might want to consider using dot notation for a query which only does one thing: 您可能要考虑对仅使用一件事的查询使用点表示法:

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

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

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()或类似内容,您将获得正确的结果。

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