.NET LINQ 查询语法与方法链 [英] .NET LINQ query syntax vs method chain

查看:25
本文介绍了.NET LINQ 查询语法与方法链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个语句是否有性能差异?

Is there any performance difference between the following two statements?

from item in collection 
where item.id == 3
select item

collection.Where(item => item.id ==3)

一般来说,LINQ 语法和方法链之间是否存在性能差异?

In general, is there any performance difference between the LINQ syntax and the method chain?

推荐答案

不,因为它们被编译成完全相同的代码.

No, because they are compiled into exactly the same code.

基本上查询表达式由编译器预处理"为没有查询表达式的C# 3",然后正常应用重载、lambda 表达式翻译等规则.这是一个非常优雅的系统,这意味着查询表达式的规则仅限于规范的一小部分.

Basically query expressions are "pre-processed" by the compiler into "C# 3 without query expressions" and then the rules of overloading, lambda expression translation etc are applied as normal. It's a really elegant system which means that the rules for query expressions are limited to just one small bit of the spec.

当然,您可以用链式方法"语法编写各种不能用查询表达式语法编写的东西,要么是由于使用了其他重载,要么是因为方法根本不受支持(例如 Count()) - 但除非您使用这些,否则编译后的代码将完全相同.为任何特定场景选择最易读的替代方案.

Of course, there are various things you can write in "chained method" syntax which can't be written in query expression syntax, either due to using other overloads or the methods simply not being supported (e.g. Count()) - but unless you're using those, the compiled code will be exactly the same. Pick the most readable alternative for any particular scenario.

这篇关于.NET LINQ 查询语法与方法链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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