.NET LINQ query syntax vs method chain

前端 未结 1 372
予麋鹿
予麋鹿 2020-11-27 16:42

Is there any performance difference between the following two statements?

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

and

相关标签:
1条回答
  • 2020-11-27 17:19

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

    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.

    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.

    0 讨论(0)
提交回复
热议问题