.NET LINQ 查询语法与方法链

编程入门 行业动态 更新时间:2024-10-09 10:27:57
本文介绍了.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 查询语法与方法链

本文发布于:2023-05-25 19:52:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/236205.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语法   方法   NET   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!