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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With