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

◇◆丶佛笑我妖孽 提交于 2019-12-04 13:16:36

问题


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


来源:https://stackoverflow.com/questions/14656600/using-predicatebuilder-is-there-a-way-to-build-a-predicate-off-of-a-variable-len

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!