简体   繁体   中英

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:

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

When I check what's inside the topThree , I find:

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

What did I do wrong and how can I correct my code?

How did you "check what's inside the 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. 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.

As suggested if you add .ToArray() or .ToList() or similar you will get the correct result.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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