当您在定义LINQ表达式时没有其中一个参数时,如何转换它

时间:2010-07-08 16:03:27

标签: c# linq lambda linq-expressions

我正在尝试在我的应用程序中构建更通用的查询功能。我想要做的是定义一个给定谓词表达式的对象可以将它应用于具有稍后将传递的值的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);
}

2 个答案:

答案 0 :(得分: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);
}

请参阅:Currying

答案 1 :(得分:0)

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

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