0

我正在尝试在我的应用程序中构建更通用的查询功能。我想做的是定义给定谓词表达式的对象,该对象可以将其应用于具有稍后将传入的值的 iqueryable。

我相信下面的代码应该证明我正在努力做的事情足以理解这个问题。如果您想了解更多详情,请告诉我!

谢谢!

//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);
}
4

2 回答 2

0

你在寻找这样的东西吗?

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

请参阅:柯里化

于 2010-07-08T16:16:20.663 回答
0

将以下代码放在 ApplyFilter 正文中:

 var f = FilterDefinition.Compile();
 return contacts.Where(x => f(x, filterValue));
于 2010-07-08T16:20:13.163 回答