Reputation: 5411
Date value
10/03/2014 77
10/02/2015 66
10/01/2016 12
10/01/2016 34
10/01/2016 55
---
---
Till 30 records
I want to write a linq Query to get Values for last 30 days plus one value before last 30 days.
So I want a response
All these records
10/01/2016 12
10/01/2016 34
10/01/2016 55
---
---
Plus one record
10/02/2015 66
Just want to know is it even possible or should I get these values in two different query. Note I am using mongodb.
Upvotes: 0
Views: 329
Reputation: 5505
With the few information:
var last30Days = sourceList.Where(rec => rec.DateField.Date >= DateTime.Today.AddDays(-30));
var firstOneAfter30Days = sourceList.Where(rec => rec.DateField.Date < DateTime.Today.AddDays(-30)).Take(1);
var allTogether = last30Days.Union(firstOneAfter30Days);
Note: Take(1)
could be FirstOrDefault()
too. You might write it in one line but this makes it more clear.
Upvotes: 1
Reputation: 9002
You could do something like the following. I have used source
to refer to your record set.
//Create your "Last 30 days" timeframe
DateTime endDate = DateTime.Now;
DateTime startDate = endDate.AddDays(-30);
//Use a query to get the "one before" record
var firstBeforeStart = source.FirstOrDefault(i => i.Date < startDate);
//Use the date of the "one before" record to calculate a query start date
var queryStart = firstBeforeStart == null ? startDate : firstBeforeStart.Date;
//Run another query to get all data based on the amended query start date
var allRecords = source.Where(i => i.Date >= queryStart && i.Date < endDate);
Upvotes: 0