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