Linq链查询执行顺序

发布于 2024-09-07 19:33:22 字数 853 浏览 6 评论 0原文

我在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天暗了我发光 2024-09-14 19:33:22

Count涉及枚举。枚举涉及执行Select,这会执行test。如果您只想计数,则根本不需要 Select,因为它不会更改元素的数量。如果您想减少查询中的 test 调用次数,请尝试将 Where 放在 Select 之前。 (.Where(..).Select(..)) 如果您的搜索谓词(lamda in where)取决于函数 test 的结果,则无法避免的电话。

Count involves enumeration. Enumeration involves execution of Select, this executes test. If you want to count only you don't need Select at all, because it doesn't change amount of elements. If you want to reduce number of test calls in your query try to put Where before Select. (.Where(..).Select(..)) if your search predicate (lamda in where) depends on results of function test then there is no way to avoid the calls.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文