LINQ查询之间的区别Lambda表达式 [英] Difference between LINQ Queries & Lambda expression

查看:94
本文介绍了LINQ查询之间的区别Lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们进行LINQ查询时,为什么要使用lambda表达式只是为了缩短代码长度,提高开发速度或还有其他任何只能由Lambda表达式实现的原因?不是通过LINQ查询.

Why to use lambda expression when we have LINQ queries just to shorten the length of code , increase the speed of development or is there any other reason which can only be achieved by Lambda expression & not by LINQ queries.

推荐答案

查询表达式仅覆盖LINQ运算符的一小部分,并且仅在涉及实际表达式时才适用,而不是(例如)具有Func<T, bool>充当谓词,在这种情况下,事情变得很丑陋.所以不用写:

Query expressions only cover a small subset of the LINQ operators, and are only applicable when you have the actual expression involved to hand, rather than (say) having a Func<T, bool> to act as the predicate, in which case things become ugly. So instead of writing:

Func<Foo, bool> predicate = ...; // Get predicate from somewhere
var query = from x in collection
            where predicate(x)
            select x;

我宁愿写:

Func<Foo, bool> predicate = ...; // Get predicate from somewhere
var query = collection.Where(predicate);

在许多其他情况下,使用非查询表达式语法更简单,尤其是在查询仅使用单个运算符的情况下.

There are various other cases where using non-query expression syntax is simpler, particularly if your query only uses a single operator.

查询表达式可以有效地转换为非查询表达式,因此您可以在非查询表达式中表达在 中可以做的所有事情.使用查询表达式使代码更简单易读.不要在不使用它们的地方使用它们.

Query expressions are effectively translated into non-query expressions, so anything you can do in query expressions can be expressed in non-query expressions. Use query expressions where they make the code simpler and more readable; don't use them where they don't.

我详细了解了 查看全文

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