bigNoob
bigNoob

Reputation:

Select current week using LINQ

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

Upvotes: 8

Views: 5749

Answers (2)

Amy B
Amy B

Reputation: 110071

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)

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062502

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;

Upvotes: 16

Related Questions