LINQ的 - 什么是找出延迟执行或不是最快的方法是什么?最快、不是、方法、LINQ

2023-09-03 10:47:39 作者:握不住的他和沙

什么是找出最快的方式.NET框架LINQ方法(如.IEnumerable LINQ方法)使用的是实现了其延迟执行与它们不使用延迟执行实现。

What is the quickest way to find out which .net framework linq methods (e.g .IEnumerable linq methods) are implemented using deferred execution vs. which are not implemented using deferred execution.

虽然编码很多次,我不知道这个人会被执行正确的方式。要知道答案,唯一的办法就是去MSDN文档,以确保。会不会有任何快捷方式,任意目录,某个地方在网络上的任何名单,任何作弊表,任何其他招了你的袖子,你可以分享吗?如果是,请这样做。这将有助于许多LINQ菜鸟(像我一样),少犯错误。唯一的其他选择是检查文档直到一个用他们足够的记住(这是对我来说很难,我倾向于不记得什么,这是记录在案的地方,并可以抬起头来:D)。

While coding many times, I wonder if this one will be executed right way. The only way to find out is go to MSDN documentation to make sure. Would there be any quicker way, any directory, any list somewhere on the web, any cheat sheet, any other trick up your sleeve that you can share? If yes, please do so. This will help many linq noobs (like me) to make fewer mistakes. The only other option is to check documentation until one have used them enough to remember (which is hard for me, I tend not to remember "anything" which is documented somewhere and can be looked up :D).

推荐答案

一般返回序列使用延迟执行方式:

Generally methods that return a sequence use deferred execution:

IEnumerable<X> ---> Select ---> IEnumerable<Y>

和返回单个对象的方法不会:

and methods that return a single object doesn't:

IEnumerable<X> ---> First ---> Y

因此​​,像其中,选择以,跳过 GROUPBY 排序依据使用,因为延迟执行他们可以,而像首先单方式了ToList 的ToArray 不要因为他们不能。

So, methods like Where, Select, Take, Skip, GroupBy and OrderBy use deferred execution because they can, while methods like First, Single, ToList and ToArray don't because they can't.

也有两种类型的延迟执行的。例如,选择方法只会得到一个项目的时候它要求生产项目,一时间,而排序依据方法将要消耗整个源时要求返回的第一个项目。因此,如果您链​​中的排序依据之后选择,执行将被推迟,直到你得到的第一个项目,但那么排序依据将要求选择所有项目。

There are also two types of deferred execution. For example the Select method will only get one item at a time when it's asked to produce an item, while the OrderBy method will have to consume the entire source when asked to return the first item. So, if you chain an OrderBy after a Select, the execution will be deferred until you get the first item, but then the OrderBy will ask the Select for all the items.