创建一个LINQ查询,该查询将包括当前周的所有条目,不包括今天和yestreday

时间:2013-02-11 09:45:55

标签: c# linq linq-to-sql

我正在研究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();

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

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分: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天。