如何在linq中创建动态lamda表达式

时间:2020-05-08 08:41:18

标签: c# linq lambda

我想通过添加where子句来过滤列表,这取决于在输入参数中where子句中所需的属性是否不为null,然后仅将其添加到where子句中,否则不添加它。如果两个都不为null,则使用两个属性进行过滤。在下面的示例中,如果有三个条件,是否可以将它们组合成一个lamda表达式?

 public class Employee
{
    public int? Property1 { get; set; }
    public int? Property2 { get; set; }

    public Employee GetEmployeeByProperty(Employee employee)
    {
        Employee filteredEmployee = new Employee();
        List<Employee> employees = new List<Employee>();
        // Logic to fill employee list

        #region Can we combine these conditions into one lamda expressoin
        if (employee.Property1 != null && employee.Property2 != null)
            filteredEmployee = employees.FirstOrDefault(r => r.Property1 == employee.Property1 && r.Property2 == employee.Property1);
        else if (employee.Property1 != null)
            filteredEmployee = employees.FirstOrDefault(r => r.Property1 == employee.Property1);
        else if (employee.Property2 != null)
            filteredEmployee = employees.FirstOrDefault(r => r.Property2 == employee.Property2); 
        #endregion

        return filteredEmployee;
    }
}

任何提示都会有所帮助。

2 个答案:

答案 0 :(得分:1)

构建.FirstOrDefault(lambda)之类的表达式,而不是使用.Where(lambda).FirstOrDefault();

        IEnumerable<Employee> employees = ...

        if (employee.Property1 != null)
            employees = employees.Where(r => r.Property1 == employee.Property1);
        if (employee.Property2 != null)
            employees = employees.Where(r => r.Property2 == employee.Property2); 

        filteredEmployee = employees.FirstOrDefault();

答案 1 :(得分:0)

不确定这是否是您真正要寻找的东西

if (employee.Property1 != null || employee.Property2 != null)
    filteredEmployee = employees.FirstOrDefault(r => 
            (employee.Property1 == null || r.Property1 == employee.Property1) &&
            (employee.Property2 == null || r.Property2 == employee.Property2))