B Vidhya
B Vidhya

Reputation: 339

Retrieve rows between the date range based on total days

I've a IQueryable result queried from the db using LINQ, now I had to filter all the rows based on a field date_sent. No. of days should be calculated from date_sent to current date. this total no. of days that falls undet 0 to 30 days range should be retrieved. How do I do it. I have the below code but it's not working. no errors but does not filter properly.

query = query.Where(x => x.DATE_SENT != null);

query = query.Where(x => (int)(EntityFunctions.DiffDays(currentDate, (DateTime)x.DATE_SENT)) >= 0 && 
                         (int)(EntityFunctions.DiffDays(currentDate, (DateTime)x.DATE_SENT)) <= 30);                                                         

Any guidance on how it can be handled will be great.

Upvotes: 1

Views: 1205

Answers (2)

M. Wiśnicki
M. Wiśnicki

Reputation: 6203

You can get it using this query.

var dtDiff = DateTime.Now.AddDays(-30);
query  = query.Where(z=>  z.DATE_SENT >= dtDiff);

31-60 days

   var dtDiff31 =DateTime.Now.AddDays(-31);
   var dtDiff60 =DateTime.Now.AddDays(-60);
   query  = query.Where(z=>  z.DATE_SENT >= dtDiff60 && z.DATE_SENT <= dtDiff31 );

Upvotes: 1

Aar&#243;nBC.
Aar&#243;nBC.

Reputation: 1330

It seems you just want to filter by a range of dates:

DateTime filterDate = currentDate.AddDays(-30);

query = query.Where(x => x.DATE_SENT >= filterDate);

In case your currentDate can vary you add the second condition:

query = query.Where(x => x.DATE_SENT >= filterDate && x.DATE_SENT < currentDate);

Upvotes: 0

Related Questions