tags:

views:

430

answers:

3

I think its easy LINQ question, but i am very new to LINQ

I have this array:

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

and i wrote this code to get top 3 elements in this array:

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

and when i check whats inside the topThree i find:

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

What i did wrong, and how to correct my code.

+5  A: 

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);
Jon Skeet
i checked it in the QuickWatch. Thanks for making things more clear.
Amr ElGarhy
QuickWatch is probably being conservative, trying not to execute code for you unless you really ask it to. The query doesn't actually have the data - it just knows how to get at the data. Fetching the data could be slow, or could have side-effects, so it's a bad idea to show that data in the debugger by default.
Jon Skeet
+1  A: 

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();
CMS
+2  A: 

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.

jonot