LINQ: Dynamic .Where() Statements

.net dynamic-linq linq

Question

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 greatly appreciated :)

Thanks,
Michael

1
1
8/2/2010 4:59:29 PM

Popular Answer

(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.

1
8/2/2010 4:58:49 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow