LINQ使用分组依次升序

时间:2018-04-11 11:19:43

标签: sql asp.net-mvc linq group-by sql-order-by

我有两个表attendancelogsemployees,结构如下;

出勤日志表:

Attendancelogs

Att_Id
Registeration_Id
DateTime
CheckType

员工表:

Employees
Id
Emp_Id
Enroll_Id

现在我要尝试的是编写一个查询,该查询将从attendancelogs获取CheckType值为&#34的所有记录;等待"并且Registeration_Id等于Enroll_IdEmployeesOrderByAcsending中的DateTime。换句话说,从RegistrationId等于Enroll_Id表中Employees及其CheckType is Pending and they should be orderbyascending according to the DateTime`

的出勤日志表中获取所有记录

我尝试的是使用foreach

的丑陋方式
//some method that populates a list
 ICollection<AttendanceLog> lstMachineInfo = manipulator.GetLogData(objZkeeper2, machineNum);
 List<Employee> empList = db.Employees.ToList();
  foreach (var emp in empList)
                        {
 var empLogs = lstMachineInfo.Where(x => x.RegisterationId == int.Parse(emp.EnrollNumber)).ToList();
 var prevDate = (from obj in empLogs select obj.Date).FirstOrDefault();
                            var prevDateTime = (from obj in empLogs select obj.DateTime).FirstOrDefault();
//and so on

在性能方面,这显然非常昂贵,而且我对优化查询的知识很少。

2 个答案:

答案 0 :(得分:1)

您可以在考勤和员工列表上尝试以下代码

var result = from attendence in AttendenceList
                   orderby attendence.DateTime
                   join employee in EmployeeList on attendence.Registeration_Id equals employee.Enroll_Id into employeejoin
                   from employ in employeejoin
                   orderby attendence.DateTime ascending
                   where attendence.Registeration_Id == employ.Enroll_Id && attendence.CheckType == "Pending"
                   orderby attendence.DateTime ascending
                   select attendence;

答案 1 :(得分:0)

这是你要找的吗?

//You are building your query to get all att ordered by date
var query = (from emp in db.Employees
             join att in db.Attendancelogs 
                 on emp.EnrollNumber equals att.RegisterationId 
             where att.CheckType.ToLower() == "pending"
             select att)
             .OrderBy(att => att.DateTime);

//You fire the query
List<Attendancelogs> attList = query.ToList();