Using PredicateBuilder is there a way to build a p

2019-03-21 15:18发布

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条回答
该账号已被封号
2楼-- · 2019-03-21 15:48

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);
}
查看更多
登录 后发表回答