I understand that it’s hard for you to understand why this line is executed in a loop
query = query.Where(expression).AsQueryable();
produces an effect similar to the "concatenation" of expressions. Short answer: it looks like why
str = str + suffix;
creates a longer string, even if it is a destination.
The longer answer is that the loop builds the expression one predicate at a time and adds Where to the sequence of conditions. Although this is an assignment, it is built from the previous state of the object, so the previous expression is not “lost” because it is used as the basis for a larger and more complex filter expression.
To understand this better, imagine that the individual expressions created by the switch are placed in an array of IQueryable objects instead of appended to query . Once the array of parts is built, you can do this:
var query = data.AsQueryable() .Where(parts[0]).AsQueryable() .Where(parts[1]).AsQueryable() ... .Where(parts[N]).AsQueryable();
Now note that each parts[i] used only once; after that, he is no longer needed. This is why you can consistently build a chain of expressions in a loop: after the first iteration, query contains a chain that includes the first member; after the second iteration, it contains the first two members, etc.
source share