代码之家  ›  专栏  ›  技术社区  ›  Vishal

我如何编写这个动态LINQ查询?

  •  1
  • Vishal  · 技术社区  · 14 年前

    基本上,我想编写一个LINQ查询来确定它们出现的天数。但是我有这六个时间过滤器——今天,昨天,当月,上月,今年,上一年。现在我有了这个我已经简化了的查询,但是在下面的这些查询之前,我实际上在不同的方面订购了这些员工,在订购之后,正如你所看到的,我分配了排名,然后同时找出他的计数(哪个可用于或不可用于以后对其进行排名-

    var result=datacontext.Employee(c=>c.Company.Id==companyId).Select((k, index) => new EmployeeDTO()
    {
      EmployeeId=k.Employee.Id,
      CompanyId=Employee.Company.Id
      PresentCount=(from e in employeeAttendance
                     where d.RecNum == k.recnum
                     && d.date_present.Year == DateTime.Today.Year
                     && d.date_present.Month == DateTime.Today.Month
                     && d.date_present.Day == DateTime.Today.Day
                     select d).Count()  
    }
    

    所以现在当过滤器说上一年我有-

    var result=datacontext.Employee(c=>c.Company.Id==companyId).Select((k, index) => new EmployeeDTO()
    {
      Position=
      EmployeeId=k.Employee.Id,
      CompanyId=Employee.Company.Id
      PresentCount=(from e in employeeAttendance
                     where d.RecNum == k.recnum
                     && d.date_present.Year == (DateTime.Today.Year-1)
    
    }
    

    如果在本月有,我有-

    var result=datacontext.Employee(c=>c.Company.Id==companyId).Select((k, index) => new EmployeeDTO()
    {
      EmployeeId=k.Employee.Id,
      CompanyId=Employee.Company.Id
      PresentCount=(from e in employeeAttendance
                     where d.RecNum == k.recnum
                     && d.date_present.Month == DateTime.Today.Month
                     && d.date_present.Year == DateTime.Today.Year
    
    }
    

    我基本上想在一个查询中将所有这些与基本上具有类似于动态子句的查询结合起来,以找出当前的计数?

    1 回复  |  直到 14 年前
        1
  •  2
  •   leppie    14 年前

    只需创建一个简单的包装器。如:

    IQueryable<EmployeeDTO> GetEmployeeCount(Expression<Func<DateTime, bool>> pred)
    {
      var result=datacontext.Employee(c=>c.Company.Id==companyId).
         Select((k, index) => new EmployeeDTO()
      {
        EmployeeId=k.Employee.Id,
        CompanyId=Employee.Company.Id,
        PresentCount=(from e in employeeAttendance
                      where d.RecNum == k.recnum && pred(d.date_present)
                      select d).Count()  
      });
      return result;
    }
    

    用途:

    var r = GetEmployeeCount(d => d.Year == (DateTime.Today.Year-1));
    
    var r = GetEmployeeCount(
       d => d.Month == DateTime.Today.Month && d.Year == DateTime.Today.Year);