-->

Using PredicateBuilder is there a way to build a p

2019-03-21 16:01发布

问题:

I have a list containing a variable number of field names. I would like to do a loop through this list and create a predicate that filters for all records that have a value in the field.

foreach (var field in FieldNames)
            {
            myPredicate= myPredicate.And(m => m.*field*!=null );                    
}   

I'm not sure how to go about doing this. Any suggestions?

TIA

回答1:

You can only write lambda expressions if you know what the properties are at compile time. Since you clearly don't know what the fields are that you want to examine, you'll have to create the expressions by hand.

You'll need a helper function like this to generate the expression:

public Expression<Func<T, bool>> GenerateFieldNotNullExpression<T>(string fieldName)
{
    var parameter = Expression.Parameter(typeof(T), "m");
    // m
    var fieldAccess = Expression.PropertyOrField(parameter, fieldName);
    // m.[fieldName]
    var nullValue = Expression.Constant(null);
    // null
    var body = Expression.NotEqual(fieldAccess, nullValue);
    // m.[fieldName] != null
    var expr = Expression.Lambda<Func<T, bool>>(body, parameter);
    // m => m.[fieldName] != null
    return expr;
}

Then use this to create your expressions and plug them in:

var predicate = PredicateBuilder.True<MyType>();
foreach (var fieldName in fieldNames)
{
    var expr = GenerateFieldNotNullExpression<MyType>(fieldName);
    predicate = predicate.And(expr);
}