Home > Software engineering >  Make Sure All Dates Are Within Same Month and Year
Make Sure All Dates Are Within Same Month and Year

Time:11-30

I have a list of dates like this and want to make sure that all dates within that list are within the same month and year. How would I accomplish that?

// Should yield true
IEnumerable<DateTime> dates1 = new List<DateTime>() { new DateTime(2022, 11, 30), new DateTime(2022, 11, 14), new DateTime(2022, 11, 2) };

// Should yield false
IEnumerable<DateTime> dates2 = new List<DateTime>() { new DateTime(2022, 11, 30), new DateTime(2022, 11, 14), new DateTime(2022, 10, 2) };

CodePudding user response:

You can compare them with the first:

DateTime firstDate = dates1.First();
bool allSameMonthAndYear = dates1
    .All(d => d.Year == firstDate.Year && d.Month == firstDate.Month);

CodePudding user response:

var listIsValid = dates1.Any() && dates1.All(e => dates1.First().Month == e.Month && dates1.First().Year == e.Year);

CodePudding user response:

Just to add an alternative:

https://dotnetfiddle.net/MJ9weK

public static bool Test( IEnumerable<DateTime> testee )
{
    return testee.GroupBy(x => new { Year = x.Year, Month = x.Month} ).Count() <= 1;
}

But this one is probably less efficient than the others. It always traverses the whole list and creates a grouping.

On the other hand, this could already give you a hint for how much the items diverge ... if that's of interest.

  •  Tags:  
  • c#
  • Related