Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Want to create lambda expression on the custom list #412

Open
Shubham041 opened this issue Aug 18, 2023 · 1 comment
Open

Want to create lambda expression on the custom list #412

Shubham041 opened this issue Aug 18, 2023 · 1 comment

Comments

@Shubham041
Copy link

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!

@zulander1
Copy link
Contributor

zulander1 commented Aug 18, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants