I’m trying to put the following logic into an Extension method that let’s me pass in a Func for the selector of the field.
public class MyClass {
public decimal someValue {get; set;}
}
public class NumericSearch {
decimal searchValue {get; set;}
// Will be =, <=, >=, >, <
string searchType {get; set;}
}
...
List<MyObject> listOfClass = { ... };
if (search.searchType == "=") {
listOfClass = listOfClass.Where(l=>l.someValue == 123).ToList();
} else if (search.searchType == "<=") {
listOfClass = listOfClass.where(l=>l.someValue <= 123).ToList();
} else if (...){
...
}
My goal is to be able to call it like this:
var filteredList = listOfClass.applyNumericSearch(l=>l.someValue, new NumericSearch() { searchValue = 123, searchType = "<="} );
So far, my method signature looks like this, but I’m not really sure how to handle the Lamda /selection portion to actually do the work I want done:
public static IEnumerable<TSource> applyNumericSearch<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector, NumericSearch search) {
Take a look at Dynamic LINQ library if you really want to use string queries.
If you’re fine with lambdas, just use different predicates:
This will not work for databases though.