John S
John S

Reputation: 8351

Using PredicateBuilder is there a way to build a predicate off of a variable length list of field names?

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

Upvotes: 4

Views: 1420

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134591

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);
}

Upvotes: 7

Related Questions