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();