当前位置: 动力学知识库 > 问答 > 编程问答 >

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.

网友答案:

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();
网友答案:

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.

网友答案:
var bestCar = (from c in cars
          orderby c.Price
          select c).FirstOrDefault()

OR

var bestCar = cars.OrderBy(c => c.Price).FirstOrDefault()
网友答案:

    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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: