Select current week using LINQ

ⅰ亾dé卋堺 提交于 2020-01-14 08:37:33

问题


How do I write the where statement that select records with Date field between Sunday to Saturday of a given date.

Data Fields: Id, Name, Date

回答1:


Where date is the date in question, how about:

    DateTime start = date.Date.AddDays(-(int)date.DayOfWeek), // prev sunday 00:00
        end = start.AddDays(7); // next sunday 00:00

    var qry = from record in data
              where record.Date >= start // include start
               && record.Date < end // exclude end
              select record;



回答2:


DateTime givenDate = DateTime.Today;
DateTime startOfWeek = givenDate.AddDays(-1 * givenDate.DayOfWeek);
DateTime endOfWeek = startOfWeek.AddDays(7);

var query = myObjects
  .Where(ob => startOfWeek <= ob.DateField && ob.DateField < endOfWeek)


来源:https://stackoverflow.com/questions/1034952/select-current-week-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!