Want to create lambda expression on the custom list
Hello,
I want to filter out the data from Redis collection via passing the expressions dynamically using where condition.
The list from which I want to filter out the cache data:
var clientlist = new List
and the model have the string value like: x.OwnerId="3179471"
-
working fine and gives the required result
redisCollections.Where(x => clientlst.Contains(x.OwnerId)); -
Does not giving the result when I am trying to do like this
public Expression<Func<CaseDataModel, bool>> GetExpression(List<string> ownerIdList) { var casedata = Expression.Parameter(typeof(CaseDataModel), "p"); var ownerProperty = Expression.Property(casedata, "OwnerId"); var owners = Expression.Constant(ownerIdList); var ownerFilter = Expression.Call(owners, "Contains", null, ownerProperty); return Expression.Lambda<Func<CaseDataModel, bool>>(ownerFilter, casedata); } var query = GetExpression(clientList); redisCollections.Where(query);
I would be grateful for any help on this issue. Thank you in advance!
This should work:
var parameter = Expression.Parameter(typeof(Customer), "b");
var property = Expression.Property(parameter, "FirstName");
var abc = new string[] { "James", "Bond" };
MethodInfo contains = typeof(Enumerable)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(x => x.Name.Contains(nameof(Enumerable.Contains)))
.Single(x => x.GetParameters().Length == 2)
.MakeGenericMethod(property.Type);
var body = Expression.Call(contains, Expression.Constant(abc), property);
var lambda = Expression.Lambda(body, parameter);
var compiled = (Func<Customer, bool>)lambda.Compile();
var results = customers.Where(compiled).ToList();