Alex Rivera | Logout

FirstOrDefault behavior directly in LINQ statement

Asked 2009-10-07T21:17:45.800
22

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.

Edit
Report

3 Answers

10

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.

answered 2009-10-07T21:22:26.870
4
var bestCar = (from c in cars
          orderby c.Price
          select c).FirstOrDefault()

OR

var bestCar = cars.OrderBy(c => c.Price).FirstOrDefault()
answered 2009-10-07T21:20:47.497
3

    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.

answered 2009-10-07T21:20:11.443

Your Answer