My problem is a bit more complicated, so I have simplified it with the below example.
Let’s say I have a simple list of Integers. I receive two condition input parameters in my function which tell me how to filter. Something like this:
public class input{
public string operation = "less than";//can be <=, >=, !=, ==,<. >, etc.
public integer filter = 9;
}
I would like to dynamically filter based on the conditions passed in, but I need to have it as an "OR" clause.
How can I dynamically create a linq query, without hard coding every single combination like this:
/*
input one = { operation = "less than" , filter = 9 }
input two = { operation = "equal to", filter =10 }
arraytoFilter { 1,2,3,4,5,6,7,8,9,10,11,12 }
*/
public int[] myFilter(input one, input two, int[] arraytoFilter){
if (one.operation == "less than" && two.operation == "equal to"){
return arraytoFilter.Where(x => x < one.filter || x == two.filter)
}
if (one.operation == "less than or equal to" && two.operation == "greater than"){
return arraytoFilter.Where(x => x <= one.filter || x > two.filter)
}
/// rest of all combinations (how do I avoid doing this???)
return arrayToFilter;
}
2
Answers
[ UPDATE 11/20 ]
This can be done without NuGet packages by building expressions using
System.Linq.Expressions
:You can use the
System.Linq.Dynamic.Core
package to write a dynamic LINQ query. Program below was tested with version 1.3.5:You should need the almighty System.Linq.Expressions to construct the expression tree and filter.
Caller method: