直接在LINQ语句中的FirstOrDefault行为 [英] FirstOrDefault behavior directly in LINQ statement

查看:80
本文介绍了直接在LINQ语句中的FirstOrDefault行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎我可能错过了一些简单的语法,但是我想直接从linq语句获取FirstOrDefault的结果,而不必先将IEnumerable存储在临时变量中.像这样:

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

我知道 first 关键字实际上并不存在,但是可以说明我想做什么. 我也知道我可以将from ... select语句包装在括号中并直接调用FirstOrDefault ,但我认为上述语法更简洁易读.

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是Enumerable类中的扩展方法之一,它没有相应的LINQ语法元素.绑定到此方法的唯一方法是通过方法调用语法.

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

这篇关于直接在LINQ语句中的FirstOrDefault行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆