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

时间:2010-10-20 17:16:33

标签: linq dynamic

基本上我想写一个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 个答案:

答案 0 :(得分:2)

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

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);