Wednesday, September 28, 2011

Only one

Just another LINQ puzzle.

Let's assume that we have sequence of objects of type Item:

class Item
{
   public int Age{get;set;}
}

How could you return all objects from the sequence that have Age value maximized (in a single LINQ query and single enumeration of the sequence)?

If the question was about returning the first object, the answer is straightforward:

return items.OrderByDescending(x=>x.Age).First();




The answer is pretty simple if you keep in mind that GroupBy operator will preserve key ordering:

var q = items.OrderByDescending(x=>x.Age).GroupBy(x=>x.Age).First();


OrderBy will enumerate the whole collection once and then keep it into internal buffer, so GroupBy will not bother source enumerable.

No comments:

Post a Comment