是否LINQ的功能顺序有关系吗? [英] Does the order of LINQ functions matter?

查看:160
本文介绍了是否LINQ的功能顺序有关系吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,这个问题的国家...没有的LINQ功能的顺序在性能方面的重要吗?明显的结果必须是相同还是...

Basically, as the question states... does the order of LINQ functions matter in terms of performance? Obviously the results would have to be identical still...

实施例

myCollection.OrderBy(item => item.CreatedDate).Where(item => item.Code > 3);
myCollection.Where(item => item.Code > 3).OrderBy(item => item.CreatedDate);



无论我返回相同的结果,但在不同的LINQ顺序。我认识到,重排一些项目将产生不同的结果,我不关心这些。什么我主要关注的是了解如果在得到同样的结果,订货会影响性能。而且,不仅仅是在2 LINQ调用我做了(排序依据,凡),但在任何LINQ要求。

Both return me the same results, but are in a different LINQ order. I realize that reordering some items will result in different results, and I'm not concerned about those. What my main concern is in knowing if, in getting the same results, ordering can impact performance. And, not just on the 2 LINQ calls I made (OrderBy, Where), but on any LINQ calls.

推荐答案

这会取决于所使用的LINQ提供程序。对于LINQ到对象,这当然可以做一个的巨大的区别。假设我们实际上已经得到了:

It will depend on the LINQ provider in use. For LINQ to Objects, that could certainly make a huge difference. Assume we've actually got:

var query = myCollection.OrderBy(item => item.CreatedDate)
                        .Where(item => item.Code > 3);

var result = query.Last();

这是需要的全部的集合进行排序和然后的过滤。如果我们有一万个项目,其中只有一个比3有一个更大的代码,我们就浪费了大量的时间排序结果这将扔掉。

That requires the whole collection to be sorted and then filtered. If we had a million items, only one of which had a code greater than 3, we'd be wasting a lot of time ordering results which would be thrown away.

相比之下,与反向操作,过滤第一:

Compare that with the reversed operation, filtering first:

var query = myCollection.Where(item => item.Code > 3)
                        .OrderBy(item => item.CreatedDate);

var result = query.Last();

这一次,我们只订购筛选的结果,这在只是一个单一的样品箱项目符合过滤器将会有很多更有效的 - 无论是在时间和空间上

This time we're only ordering the filtered results, which in the sample case of "just a single item matching the filter" will be a lot more efficient - both in time and space.

它还可以的使查询是否有差别正确或不执行。试想一下:

It also could make a difference in whether the query executes correctly or not. Consider:

var query = myCollection.Where(item => item.Code != 0)
                        .OrderBy(item => 10 / item.Code);

var result = query.Last();

这很好 - 我们知道我们会不会被0来划分但是,如果我们进行排序的筛选,查询会抛出异常。

That's fine - we know we'll never be dividing by 0. But if we perform the ordering before the filtering, the query will throw an exception.

这篇关于是否LINQ的功能顺序有关系吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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