1
votes

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#?

1
Did you have a question?Lubo Antonov
What if you show what your IEnumerable contains?JotaBe
What are you having trouble with exactly? The grouping or the condition to include an event or not?Meta-Knight
I just need help with the condition to include or exclude a date. I only mentioned the grouping to give context to what I'm using the code for.skeletank

1 Answers

3
votes

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!