简体   繁体   中英

Get dates from the current calendar month and the next 11 coming months

I have an IEnumerable<DateTime> . I would like to pull out all dates that occur in the current calendar month even if they have passed as well as all dates in the next 11 calendar months. I'll be displaying the dates grouped by month starting with the most recent. For example:

Current Date - Mar 12 2012

  • March 2012
    • March 3 - Event 1
    • March 15 - Event 2
    • March 30 - Event 3
  • ...
  • ...
  • ...
  • February 2013
    • Feb 3 - Event 156
    • Feb 13 - Event 157
    • Feb 20 - Event 158

I already know how to do the grouping part. How would you accomplish filtering the dates using linq and C#?

Something like this should work. You first determine the legal range of dates, then filter out any dates that are outside of that range, and finally you group them by month.

I wrote the following code by hand, you may need to tweak it:

var acceptableFirstDate = DateTime.Today;
if (DateTime.Today.Day > 1)
{
    acceptableFirstDate = DateTime.Today.AddDays(-DateTime.Today.Day + 1);
}
var acceptableLastDate = acceptableFirstDate.AddMonths(12).AddDays(-1);

var result = dates
    .Where(x => x >= acceptableFirstDate && x <= acceptableLastDate)
    .GroupBy(x => x.Month);

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM