如何为具有额外参数的LINQ where子句创建可重用函数

时间:2017-10-21 20:26:23

标签: c# linq

我想做这样的事情:

const string user = "Jim";
var emps = employees.Where(FilterEmployees(user));

Func<Employee, string, bool> FilterEmployeesType = FilterEmployees;
static bool FilterEmployees(Employee e, string username)
{
    return e.Username.ToUpper() == username.ToUpper() && !e.Deleted;
}

如果委托的签名仅包含 Employee ,则此方法有效。我怎样才能传递另一个值?

只是澄清一下,这对我有用:

var emps = employees.Where(e => !e.Deleted);

或转换为调用委托/函数后:

var emps = employees.Where(FilterEmployees);

Func<Employee, bool> FilterEmployeesType = FilterEmployees;
static bool FilterEmployees(Employee e)
{
    return !e.Deleted;
}

但是,我还想将一个额外的参数传递给函数,以便它可以处理这种情况:

const string user = "Jim";
var emps = employees.Where(e => e.Username.ToUpper() == user.ToUpper() && !e.Deleted);

如何将变量 user 添加到函数中?

1 个答案:

答案 0 :(得分:2)

如果让函数返回谓词,而不是直接将它用作谓词,则可以传递在其正文中传递的任何参数:

static Func<Employee,bool> FilterEmployees(string username)
{
    return e => e.Username.ToUpper() == username.ToUpper() && !e.Deleted; //small sidenote: performance wise this could be tweaked, by at the least putting `username = username.ToUpper()` outside the lambda instead having it done on each call
}

通过上述内容,您可以使用示例var emps = employees.Where(FilterEmployees(user));

也是一个小的补充(可能不是你需要的,但为了提及它):另一种方法是让Filter方法进行实际过滤(充当where) ,通过让它返回改变的可枚举(为了便于使用,将其声明为扩展方法):

public static IEnumerable<Employee> FilterEmployees(this IEnumerable<Employee> employees, string username)
{
    return employees.Where(e => e.Username.ToUpper() == username.ToUpper() && !e.Deleted);
}

如果将上述内容放在可访问的静态类中,则可以将调用写为:var emps = employees.FilterEmployees(user);