开发者

Extension method with Lambda/Selector/Predicate logic

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:

开发者_Python百科
public static IEnumerable<TSource> applyNumericSearch<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector, NumericSearch search) {


public static IEnumerable<TSource> applyNumericSearch<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, decimal> selector,
    NumericSearch search
) {
    var projection = source.Select(x => selector(x));
    if(search.searchType == "<=") {
        return projection.Where(y => y <= search.searchValue);
    }
    // etc.
}

Additionally, I strongly consider making searchType an instance of an enum

public enum SearchType {
    LessThan,
    LessThanOrEqual,
    Equal,
    GreaterThan,
    GreaterThanOrEqual,
    NotEqual
 };

instead of using string.


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:

Func<decimal, bool> BuildPredicate (NumericSearch search)
{
    switch (search.Kind) {
        case SearchKind.Equal:
            return (x => x == search.Value);
        case SearchKind.LessThan:
            return (x => x < search.Value);
        // ...
    }
}

// in ApplyNumericSearch
var predicate = BuildPredicate (search);
return source.Where (x => predicate (selector (x));

This will not work for databases though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜