tags:

views:

226

answers:

4

Seems like I may have missed something simple in the syntax, but I'd like to get the results of FirstOrDefault from a linq statement directly without having to store the IEnumerable in a temporary variable first. Something like this:

var bestCar = from c in cars
              orderby c.Price
              select first c

I know the first keyword doesn't actually exist but illustrates what I'd like to do. I also know I can wrap the from...select statement in parenthesis and call FirstOrDefault directly but I think the above syntax is cleaner and easier to read.

+2  A: 

    var bestCar = (from c in cars
              orderby c.Price
              select c).FirstOrDefault();

Sorry I didn't read your question entirely, it seems that this may be exactly what you don't want to do.

Dave
+2  A: 
var bestCar = (from c in cars
          orderby c.Price
          select c).FirstOrDefault()

OR

var bestCar = cars.OrderBy(c => c.Price).FirstOrDefault()
Nate
+4  A: 

Enumerable.FirstOrDefault is one of the extension methods in the Enumerable class which does not have a corresponding LINQ syntax element. The only way to bind to this method is via method call syntax.

You can avoid the temporary by doing the follownig

var bestCar = (from c in cars
              orderby c.Price
              select c).FirstOrDefault();
JaredPar
+1  A: 

There isn't a way to do that. LINQ is used for defining a query. Doing that doesn't actually cause an evaluation, whereas executing FirstOrDefault (or enumerating over it) executes the query.

Adam Robinson
Downvoter care to comment why? I answered the question (no, there is no such keyword) and explained why.
Adam Robinson
(upvoted to offset the uncalled-for downvote)
Nate