views:

40

answers:

2

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 me 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);
}
A: 

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

dtb
thanks dtb, that was exactly what I really needed to do.
eoldre
A: 

Place the following code in your ApplyFilter body:

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