英文:
How do I find the top 5 rows of a LINQ query result?
问题
这个查询似乎不正常,似乎它无法识别条件 DueDate.Month == current_month - 1
。有谁知道如何更正这个查询?
英文:
I have an ASP.NET Core MVC app that contains two entities: Employee
and Task
. These entities have a one-to-many relationship.
A Task
consists of an assignee (the Employee
assigned to work on it) and a due date, among other properties.
I need to display the 5 employees who completed the largest number of tasks in the past month.
I tried the following:
public async Task<IActionResult> Display()
{
int current_month = DateTime.Now.Month;
var employees = _context.Employees
.Include(t => t.EmployeeTasks)
.OrderByDescending(x =>
x.EmployeeTasks.Count(x => x.DueDate.Month == current_month - 1))
.Take(5);
return View(employees);
}
This query is not working properly, as if it does not recognize the condition
This query isn't working properly - it seems like it doesn't recognize the condition
<br>
DueDate.Month == current_month - 1
.
Does anyone know how to correct this query?
答案1
得分: 0
使用current_month变量来按截止日期筛选任务可能会引发查询问题。如果当前月份是一月(其值为1),从current_month中减去1可能不会始终产生预期的结果。
为了解决这个问题,您可以修改查询,根据DateTime属性Month和Year来筛选任务的截止日期。使用以下查询,您可以筛选上个月到期的任务。
// 获取上个月的开始和结束日期
var currentDate = DateTime.Now;
var startDate = new DateTime(currentDate.Year, currentDate.Month, 1).AddMonths(-1);
var endDate = startDate.AddMonths(1).AddDays(-1);
// 获取在上个月完成了最多任务的前5名员工
var employees = await _context.Employees
.Include(e => e.EmployeeTasks)
.OrderByDescending(e => e.EmployeeTasks.Count(t => t.DueDate >= startDate && t.DueDate <= endDate))
.Take(5)
.ToListAsync();
不要翻译代码部分。
英文:
Using the current_month variable to filter tasks by due date might be causing the query issue. If the current month is January (which has a value of 1), subtracting 1 from current_month might not always result in the expected result.
To resolve this issue, you can modify the query to filter tasks based on their due dates using the DateTime properties Month and Year. Using the following query, you can filter tasks due in the previous month
// Get the start and end dates of the previous month
var currentDate = DateTime.Now;
var startDate = new DateTime(currentDate.Year, currentDate.Month, 1).AddMonths(-1);
var endDate = startDate.AddMonths(1).AddDays(-1);
// Retrieve the top 5 employees who completed the most tasks in the previous month
var employees = await _context.Employees
.Include(e => e.EmployeeTasks)
.OrderByDescending(e => e.EmployeeTasks.Count(t => t.DueDate >= startDate && t.DueDate <= endDate))
.Take(5)
.ToListAsync();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论