创建一个LINQ查询,该查询将包括本周的所有条目,不包括今天和昨天
本文关键字:查询 昨天 今天 不包括 一个 创建 LINQ 包括本 | 更新日期: 2023-09-27 17:58:33
我正在进行LINQ查询,以检索本周的所有记录,但是,我需要排除今天和昨天的任何记录。
以下是我目前所拥有的:
DateTime startThisWeek = DateFunctions.GetFirstDayOfWeek(DateTime.Now).AddDays(1);
DateTime endOfThisWeek = startThisWeek.AddDays(6);
DateTime today = DateTime.Now;
DateTime yesterday = DateTime.Now.AddDays(-1);
var notificationList =
(from n in db.DashboardNotifications
.OrderByDescending(n => n.NotificationDateTime)
where (n.NotificationDateTime >= startThisWeek &&
n.NotificationDateTime <= endOfThisWeek) &&
(n.NotificationDateTime != today &&
n.NotificationDateTime != yesterday)
select n).ToList();
上述查询的问题是它没有返回正确的记录,还显示了今天的记录。
假设您的DateFunctions.GetFirstDayOfWeek
工作正常
DateTime startThisWeek = DateFunctions.GetFirstDayOfWeek(DateTime.Now);
DateTime yesterday = DateTime.Today.AddDays(-1);
var notificationList =
(from n in db.DashboardNotifications
where n.NotificationDateTime.Date >= startThisWeek.Date &&
n.NotificationDateTime.Date < yesterday)
orderby n.NotificationDateTime descending
select n).ToList();
评论:若本周的开始时间不在昨天之前,那个么您将不会得到任何记录。否则昨天总是在本周末之前。
如何正确开始本周:
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime date,
DayOfWeek startOfWeek = DayOfWeek.Monday)
{
DateTime result = date;
while (result.DayOfWeek != startOfWeek)
result = date.AddDays(-1);
return result.Date;
}
}
只有当今天和昨天的记录与运行报告时的时间相同时,才排除它们。
尝试
DateTime startThisWeek = DateFunctions.GetFirstDayOfWeek(DateTime.Now.Date).AddDays(1);
DateTime endOfThisWeek = startThisWeek.AddDays(6);
DateTime today = DateTime.Now.Date;
DateTime yesterday = DateTime.Now.Date.AddDays(-1);
var notificationList =
(from n in db.DashboardNotifications
.OrderByDescending(n => n.NotificationDateTime)
where (n.NotificationDateTime >= startThisWeek &&
n.NotificationDateTime.Date <= endOfThisWeek) &&
(n.NotificationDateTime.Date != today &&
n.NotificationDateTime.Date != yesterday)
select n).ToList();
这是假设将来有可能发出通知。
Ps,我不确定DateFunctions是什么。GetFirstDayOfWeek方法没有,也没有为什么要添加1天。