过滤条件使用LINQ进行搜索

时间:2016-03-08 18:33:56

标签: c# linq

我对LINQ查询'更新'还有另一个问题,我有什么事情要进行,但不确定这是否是最有效的方法。在我的项目中,我正在使用一个真正的数据库,但为了简单起见,我将把它简化为一个简单的员工列表:

var employees = new List<Employee>
        {
            new Employee { Id = 0, firstName = "James", LastName = "Bond", Manager = "M", StartDate = DateTime.Now },
            new Employee { Id = 1, firstName = "Eric", LastName = "Bond", Manager = "M", StartDate = DateTime.Now },
            new Employee { Id = 2, firstName = "Sue", LastName = "Milton", Manager = "Q", StartDate = DateTime.Now },
            new Employee { Id = 3, firstName = "Olivia", LastName = "Milton", Manager = "M", StartDate = DateTime.Now },
            new Employee { Id = 4, firstName = "Alice", LastName = "Raymond", Manager = "M", StartDate = DateTime.Now },
            new Employee { Id = 5, firstName = "James", LastName = "Skywalker", Manager = "M", StartDate = DateTime.Now },
            new Employee { Id = 6, firstName = "Luke", LastName = "Skywalker", Manager = "M", StartDate = DateTime.Now },

        };

我必须根据给定的标准在此列表中进行搜索..其中,条件是各种字段与OR的组合以及AND字段中的操作,例如,让我所有员工在哪里:

  • firstName =“James” OR “eric” AND manager =“Q”
  • lastname =“bond” OR “Martha”
  • firstName =“James” AND 姓氏=“债券” 等等...

这将是一个Web API调用,我必须在一个方法中执行此操作。另一个挑战是每个搜索参数都是“可选的”,即他们可以传递一个名字和管理员名称的列表,并忽略姓氏参数等。所以这就是我开始编码的内容:

    public IList<Employee> GetFilteredEmployees(IList<String> firstnames = null,
                                                IList<String> lastnames = null,
                                                IList<String> managers = null)
    {
    if (firstnames != null && firstnames.Any())
     {
          foreach (var fn in firstnames)
          {
             employeeByFn = employees.Where(emp => emp.firstName == fn).ToList<Employee>();
          }

      }

     if (lastnames != null && lastnames.Any())
     {
         foreach (var ln in lastnames)
         {
             employeeByLn = employees.Where(emp => emp.LastName == ln).ToList<Employee>();
         }
      }

     ..... // code ellided
    }

正如您所看到的,即使使用一些搜索条件参数,这也会变得很难看。在我的真实项目中,我有多达16个。同样在所有这些子查询的最后,我必须将我的结果合并到一个员工列表中并返回,请记住任何子查询结果可能为空。

我确信这不是一个独特的问题,我之前会看到类似的问题,但不是完全相同的问题。这样做的优雅方式也很容易维护。即如果他们决定稍后添加更多搜索条件(比如开始日期),我希望能够轻松修改我的方法来处理它。

非常感谢一群人。

1 个答案:

答案 0 :(得分:5)

您可以继续在同一结果上添加Where()条件,而不是创建许多部分结果。

public IList<Employee> GetFilteredEmployees(IList<String> firstnames = null,
                                            IList<String> lastnames = null,
                                            IList<String> managers = null)
{
    IQueryable<Employee> result = employees;

    if (firstnames != null)
        result = result.Where(emp => firstnames.Contains(emp.firstName));

    if (lastnames != null)
        result = result.Where(emp => lastnames.Contains(emp.LastName));

    if (managers != null)
        result = result.Where(emp => managers.Contains(emp.Manager));

    ... // code ellided

    return result.ToList();
}