I want to get all dates in the last three months, so I did the following:
protected void BindPermissions(int empNum)
{
var permPeriod = new Dictionary<int, int>();
permPeriod.Add(DateTime.Now.Year, DateTime.Now.Month);
permPeriod.Add(DateTime.Now.AddMonths(-1).Year, (DateTime.Now.AddMonths(-1).Month));
permPeriod.Add(DateTime.Now.AddMonths(-2).Year, (DateTime.Now.AddMonths(-2).Month));
var dt = payload_object.AttendancePermissionBO.permissionList
.Where(x => x.empNum == empNum
&& ((x.permDate.Year == permPeriod.Keys.ElementAtOrDefault(0) && x.permDate.Month == permPeriod.Values.ElementAtOrDefault(0)) ||
(x.permDate.Year == permPeriod.Keys.ElementAtOrDefault(1) && x.permDate.Month == permPeriod.Values.ElementAtOrDefault(1)) ||
(x.permDate.Year == permPeriod.Keys.ElementAtOrDefault(2) && x.permDate.Month == permPeriod.Values.ElementAtOrDefault(2)))).ToList().OrderBy(x => x.permDate);
GV_PermissionHistory.DataSource = dt;
GV_PermissionHistory.DataBind();
}
Is there a better way to do that or this method suits what i need?
3
Answers
permDate
that after (inclusive) the date from 3 months ago.Updated:
This answer is for querying records from the last 3 months ago until the current date.
Based on Post Owner’s requirements and existing code, what he needs is from
Hence @Astrid’s answer is most accurate.
You can use the below code for all the dates of last X- months. You can do some changes based on your requirements.
It seems like you do not really want all dates in the last three months, but you want all items in your collection where
permDate
is a date within some date range.Given your own approach, that some date range seems to be the two previous months plus the entire current month. I.e. for 5th of July 2022, the date range is all of May, June and July 2022.
I think you can simplify your approach by defining a start date and an end date, and compare the
permDate
values with those two values. A straight-forward way of doing that could be:Then, you can use
startDate
andendDate
in your filtering: