How to create predicate dynamically

后端 未结 3 1675
感动是毒
感动是毒 2020-12-17 19:23

Hi i want to create a list based on the search string using predicate expressions.

I have a list of type products contains different names.

List

3条回答
  •  甜味超标
    2020-12-17 19:42

    Initialize the predicate as false

    Expression> predicate = PredicateBuilder.False();
    

    You need to combine the predicates using Or

    foreach (string str in SearchItems)
    {
        string temp = str;
        predicate = predicate.Or(p => p.NameToLower().Contains(temp.ToLower()));                   
    }
    

    Source for predicate builder here. It is part of LINQKit

    Code, in case link goes

    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Collections.Generic;
    
    public static class PredicateBuilder
    {
      public static Expression> True ()  { return f => true;  }
      public static Expression> False () { return f => false; }
    
      public static Expression> Or (this Expression> expr1,
                                                          Expression> expr2)
      {
        var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast ());
        return Expression.Lambda>
              (Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
      }
    
      public static Expression> And (this Expression> expr1,
                                                           Expression> expr2)
      {
        var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast ());
        return Expression.Lambda>
              (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
      }
    }
    

提交回复
热议问题