2

我正在处理 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();

上面查询的问题是它没有返回正确的记录,它也显示了今天的记录。

4

2 回答 2

2

假设你的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;
    }
}
于 2013-02-11T10:32:25.443 回答
1

如果今天和昨天的记录与您运行报告时的时间相同,您只会排除它们。

尝试

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 天。

于 2013-02-11T10:34:49.367 回答