LINQ: Dynamic .Where() Statements
Scenario: I have a list and three search filters. Something like:
ResultList = OriginalList.Where(filter1).Where(filter2).Where(filter3);
Question: Can I update filter 3, and then have the ResultList update, without having LINQ running filter1 and filter2? (I want to improve performance)
Basically, it would be the same as:
Result1 = OriginalList.Where(filter1).Where(filter2);
Result2 = Result1.Where(filter3);
UpdateFilter3(); // Just changes the filter somehow
Result2 = Result1.Where(filter3);
return Result2;
This just is a little cumbersome to keep track of, and I was wondering if there is a smarter way to do this? I looked at Continuous LINQ (CLINQ: http://clinq.codeplex.com/), however, it seems that it just basically tells the LINQ to refresh the whole WHERE statement everytime just one of the filters change.
Any words of wisdom are gre开发者_如何学Pythonatly appreciated :)
Thanks,
Michael(Assumption: you used a variable name OriginalList
rather than OriginalQuery
or something like that, so I assume we're talking about straight LINQ-To-Object and IEnumerable here.)
Yes you can, by making Result1 a List rather than IEnumerable. Like this:
Result1 = OriginalList.Where(filter1).Where(filter2).ToList();
Result2 = Result1.Where(filter3);
UpdateFilter3(); // Just changes the filter somehow
Result2 = Result1.Where(filter3);
return Result2;
As a List, Result1
isn't just an IEnumerable waiting to go, but an actual solid list of stuff, with filter1
and filter2
permanently applied, so to speak. When line 4 executes above, it will still be off of the solid List that you created on line 1. You could swap out filter 3 and reapply to Result1 a hundred times, and filter1
and filter2
will still only have been applied once.
There is a cost to creating the list, but this will be more than made up for when reapplying multiple filter3
filters, especially if filter1
and filter2
are complicated or substantially reduce the set.
精彩评论