Linq链查询执行顺序
我在使用 linq 时遇到了一些性能问题,这让我想到了我的第一个 stackoverflow 问题:
以下代码中的测试函数对于这两个 linqs 查询执行了不同的次数:
int[] mydata = { 1 , 2, 34, 5, 67, 8 };
var query = from i in mydata select new { i,v=test(i)};
var query2 = query.Where(v=>v.v == 2);
MessageBox.Show(query2.Count().ToString());
var query = from i in mydata where i==2 select new { i,v=test(i)};
MessageBox.Show(query.Count().ToString());
还有 Count() 函数,真的需要评估 select 部分吗?这也意味着执行 query2.Select(i=>i) 将触发 test() 调用
如果这是要执行的方法,要执行类似调用的延迟过滤器,则应更改第二个查询以减少不必要的测试() 调用:
var query = from i in mydata where (filter ? v=filtevalue : true) select new { v=test(i)};
MessageBox.Show(query.Count().ToString());
我需要执行的是构建一个大查询,然后在程序的不同部分过滤数据,而不对被过滤的数据执行 Select 部分(以避免性能损失)。这可能吗?
提前致谢。
I'm experiencing some performance issues using linq, that led me to my first stackoverflow question:
The test function in the following code, is executed a differente number of times for these two linqs queries:
int[] mydata = { 1, 2, 34, 5, 67, 8 };
var query = from i in mydata select new { i,v=test(i)};
var query2 = query.Where(v=>v.v == 2);
MessageBox.Show(query2.Count().ToString());
var query = from i in mydata where i==2 select new { i,v=test(i)};
MessageBox.Show(query.Count().ToString());
Also the Count() function, does really need to evaluate the select part?. This also means that perform a query2.Select(i=>i) will fire the test() call a
If this is the way to go, to perform a deferred filter like call, the second query should be changed to reduce unnecesary test() calls to:
var query = from i in mydata where (filter ? v=filtevalue : true) select new { v=test(i)};
MessageBox.Show(query.Count().ToString());
What I need to perform is to build a big query, an then filter data at different parts of the program without executing the Select part for the data that is filterout (to avoid the performance penalty). Is this possible?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Count
涉及枚举。枚举涉及执行Select
,这会执行test
。如果您只想计数,则根本不需要Select
,因为它不会更改元素的数量。如果您想减少查询中的test
调用次数,请尝试将Where
放在Select
之前。 (.Where(..).Select(..)
) 如果您的搜索谓词(lamda in where)取决于函数test
的结果,则无法避免的电话。Count
involves enumeration. Enumeration involves execution ofSelect
, this executestest
. If you want to count only you don't needSelect
at all, because it doesn't change amount of elements. If you want to reduce number oftest
calls in your query try to putWhere
beforeSelect
. (.Where(..).Select(..)
) if your search predicate (lamda in where) depends on results of functiontest
then there is no way to avoid the calls.