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)}; 开发者_Go百科
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.
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.
精彩评论