0

I am trying to loop only 3 times through a C# List.This is my code so far.

IEnumerable<Artist> threeoldest = Artists.Where(Artist=> Artist.Hometown == "Atlanta").OrderByDescending(Artist=>Artist.Age); 

I only want to get the first 3 rows, since the list is already in descending order.

for(int i = 0; i <= 2; i++)
{                 
    System.Console.WriteLine(threeoldest[i].RealName);                 
    System.Console.WriteLine(threeoldest[i].Age);        
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
Faizan Rahman
  • 59
  • 3
  • 7

1 Answers1

4

Use Take to truncate the elements from the IEnumerable:

Artists.Where(Artist=> Artist.Hometown == "Atlanta")
       .OrderByDescending(Artist => Artist.Age)
       .Take(3);
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • 4
    You should order first and then take. – Péter Csajtai Nov 07 '18 at 20:31
  • 2
    In the case you want the first 3 items? you don't want to only sort 3 items you accidently get by the Select but you want to sort all items and than take the first 3 – derHugo Nov 07 '18 at 20:32
  • 1
    @Aomine No we are not. OrderBy is lazy, just like most other LINQ methods. It is implementation detail of course, but if the sorting algorithm can determine the top 3 elements it can stop right there without having to sort the remaining ones. But either way, the OP wanted to take the first 3 artists by age descending from Atlanta, and that's how you do it – Marcell Toth Nov 07 '18 at 20:33
  • @PéterCsajtai got it now, my bad. thanks! – Ousmane D. Nov 07 '18 at 20:36
  • 1
    https://github.com/morelinq/MoreLINQ/blob/20f56c2654ea24dad54c18f3683a8772ff734772/MoreLinq/Extensions.g.cs#L3657 might be an approach to consider if you want to avoid holding the entire sorted list in memory @MarcellTóth. – mjwills Nov 07 '18 at 20:48