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 に答える