linq - 如何以及在何处使用 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; }
}
解决方案
实际问题与 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
{
...
})
);
...
推荐阅读
- python - 如何在 matplotlib 条形图中的条形上方显示 Y 值?
- startactivityforresult - 在扩展 View 而不是扩展 AppCompatActivity 的类中使用 startActivityForResult 方法?
- python - Python:创建一个使用多进程工作池来回答查询的微服务
- swift - 为什么几何阅读器不将其孩子居中?
- javascript - 使用基于索引的 replace() 更改 Javascript 中的字符串
- ssl - 禁用 ACMEv1 上的 Letsencrypt 错误帐户创建
- windows - 无法将“gatsby-plugin-netlify-cms”插件安装到 Gatsby 博客
- mysql - 变量以错误的方式切割,但现在确定为什么?
- sql - 是否可以在 Spring 中捕获自定义的 oracle sql 触发器异常并将其传递给 React?
- java - 使用 Rapid API 为 Android 订阅 Kairos