我正在使用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;
    }
}

10-05 21:36