redis-om-dotnet icon indicating copy to clipboard operation
redis-om-dotnet copied to clipboard

Want to create lambda expression on the custom list

Open Shubham041 opened this issue 2 years ago • 1 comments

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 { "3179471", "123456" };

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!

Shubham041 avatar Aug 18 '23 11:08 Shubham041

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

zulander1 avatar Aug 18 '23 17:08 zulander1