开发者

How to Transform a LINQ Expression when you do not have one of the parameters when you define it

开发者 https://www.devze.com 2023-01-06 00:12 出处:网络
I\'m trying to build more generic query functionality into my application. What I\'d like to do is define objects which given an predicate expression can apply that to an iqueryable with a value that

I'm trying to build more generic query functionality into my application. What I'd like to do is define objects which given an predicate expression can apply that to an iqueryable with a value that will be passed in later.

I believe the code below should demonstrate what I'm trying to do well enough to understand the problem. Please let m开发者_如何学Pythone know if you'd like more details!

Thanks!

//in practice the value of this would be set in object constructor likely
private Expression<Func<Contact, string, bool>> FilterDefinition = (c, val) => c.CompanyName.Contains(val);

//this needs to filter the contacts using the FilterDefinition and the filterValue. Filterval needs to become the string parameter
private IQueryable<Contact> ApplyFilter(IQueryable<Contact> contacts, string filterValue)
{
     //this method is what I do know know how to contruct.
     // I need to take the FilterDefinition expression and create a new expression that would be the result if 'filtervalue' had been passed into it when it was created.
     //ie the result would be (if 'mycompany' was the value of filterValue) an expression of
     //  c => c.CompanyName.Contains("mycompany")
     Expression<Func<Contact, bool>> usableFilter = InjectParametersIntoCriteria(FilterDefinition, "SomeCompanyName");

     //which I could use the results of to filter my full results.
     return contacts.Where(usableFilter);
}


Are you looking for something like this?

private Func<string, Expression<Func<Contact, bool>>> FilterDefinition =
    val => c => c.CompanyName.Contains(val);

private IQueryable<Contact> ApplyFilter(
    IQueryable<Contact> contacts, string filterValue)
{
    Expression<Func<Contact, bool>> usableFilter = FilterDefinition(filterValue);

    return contacts.Where(usableFilter);
}

See: Currying


Place the following code in your ApplyFilter body:

 var f = FilterDefinition.Compile();
 return contacts.Where(x => f(x, filterValue));
0

精彩评论

暂无评论...
验证码 换一张
取 消