Paul Alexander
Paul Alexander

Reputation: 32367

FirstOrDefault behavior directly in LINQ statement

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.

Upvotes: 22

Views: 10558

Answers (5)

Pao'lino
Pao'lino

Reputation: 59

In VB you can use 'Aggregate':

Dim BestCar = Aggregate c In cars
              Order By c.Price
              Into FirstOrDefault

Upvotes: 2

David
David

Reputation: 19677


    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.

Upvotes: 3

Adam Robinson
Adam Robinson

Reputation: 185623

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.

Upvotes: 10

JaredPar
JaredPar

Reputation: 754585

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

Upvotes: 34

Nate
Nate

Reputation: 1669

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

OR

var bestCar = cars.OrderBy(c => c.Price).FirstOrDefault()

Upvotes: 4

Related Questions