首页 > 解决方案 > 如何以及在何处使用 AddRange() 方法

问题描述

我想显示第二个表中的相关数据以及第一个表中的每个值

我试过这个查询

public ActionResult Index()
    {            
        List<EmployeeAtt> empWithDate = new List<EmployeeAtt>();

        var employeelist = _context.TblEmployee.ToList();

        foreach (var employee in employeelist)
        {               
            var employeeAtt = _context.AttendanceTable
                .GroupBy(a => a.DateAndTime.Date)
                .Select(g => new EmployeeAtt
                   {
                     Date = g.Key,
                     Emp_name = employee.EmployeeName,
                     InTime = g.Any(e => e.ScanType == "I") ? g.Where(e => 
                     e.ScanType == "I").Min(e => 
                     e.DateAndTime.ToShortTimeString())
                     .ToString() : "Absent",
                     OutTime = g.Any(e => e.ScanType == "O") ? g.Where(e => 
                     e.ScanType == "O").Max(e =>
                     e.DateAndTime.ToShortTimeString())
                     .ToString() : "Absent"                                                         
                    });

            empWithDate.AddRange(employeeAtt);
        }
        return View(empWithDate);
    }  

这是我的出勤表

考勤表

结果

我想用“I”列值显示每个员工的最短时间,最后一次用“O”列值作为下班时间。我想我没有在适当的地方使用 AddRange()。那它应该去哪里?

public partial class TblEmployee
{
    public TblEmployee()
    {
        AttendanceTable = new HashSet<AttendanceTable>();
    }

    public int EmpId { get; set; }
    public string EmployeeName { get; set; }

    public virtual ICollection<AttendanceTable> AttendanceTable { get; set; }
}

 public partial class AttendanceTable
{
    public int Id { get; set; }
    public int AttendanceId { get; set; }
    public int EmployeeId { get; set; }
    public string ScanType { get; set; }
    public DateTime DateAndTime { get; set; }

    public virtual TblEmployee Employee { get; set; }
}

标签: linqentity-framework-core

解决方案


实际问题与 AddRange() 无关,您需要在 GroupBy() 之前使用 where 子句来将出勤(分组之前)限制为仅与该特定员工相关的记录,例如

_context.AttendanceTable
        .Where(a => a.Employee == employee.EmployeeName)
        .GroupBy(a => a.DateAndTime.Date)
        ...

根据您的模型,如果可能,最好使用某种 ID 而不是 EmployeeName 进行比较。

您也可以使用 SelectMany() 而不是 for 循环和 AddRange() 将结果组合到一个列表中。像这样:

List<EmployeeAtt> empWithDate = _context.TblEmployee.ToList()
            .SelectMany(employee => 
                            _context.AttendanceTable
                                    .Where(a => a.Employee == employee.EmployeeName)
                                    .GroupBy(a => a.DateAndTime.Date)
                                    .Select(g => new EmployeeAtt
                                                 {
                                                     ...        
                                                 })
                       );
...

推荐阅读