Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

.net-3.5

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?

like image 368
Amr Elgarhy Avatar asked Jul 23 '09 05:07

Amr Elgarhy


1 Answers

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);
like image 103
Jon Skeet Avatar answered Sep 29 '22 01:09

Jon Skeet