I have a list of months in which users are required to update some data. I want to determine at what date they should have updated their data. They must update in March, May and August. If today is March, I want to get back the 1st of March. If today is February, I want to get back last year's August. In reality the list wouldn't be hardcoded.
I do have some working code, but I wonder if there is a simpler / more elegant of writing this (the GetCheckDate
method).
using System;
using System.Collections.Generic;
using System.Linq;
internal class Program
{
private static void Main()
{
var listOfMonths = new List<int?> {3, 5, 8};
Console.WriteLine(GetCheckDate(listOfMonths,
new DateTime(2014, 2, 1))); // expect 2013-08-01
Console.WriteLine(GetCheckDate(listOfMonths,
new DateTime(2014, 3, 1))); // expect 2014-03-01
Console.WriteLine(GetCheckDate(listOfMonths,
new DateTime(2014, 7, 1))); // expect 2014-05-01
Console.WriteLine(GetCheckDate(null,
new DateTime(2014, 7, 1))); // expect 2013-07-1
Console.WriteLine(GetCheckDate(new List<int?>(),
new DateTime(2014, 7, 1))); // expect 2013-07-1
}
private static DateTime GetCheckDate(IEnumerable<int?> listOfMonths,
DateTime curDate)
{
DateTime result = curDate.AddYears(-1);
if (listOfMonths == null) return result;
listOfMonths = listOfMonths.ToList();
if (!listOfMonths.Any()) return result;
listOfMonths = listOfMonths.OrderByDescending(m => m).ToList();
var greatestSmallerThan =
listOfMonths.FirstOrDefault(m => m <= curDate.Month)
?? listOfMonths.FirstOrDefault(m => m > curDate.Month);
result = new DateTime(
greatestSmallerThan.Value <= curDate.Month
? curDate.Year : curDate.Year - 1, greatestSmallerThan.Value, 1);
return result;
}
}
curDate.AddYears(-1)
(edited). What I'd like to know is how to efficiently determine the date. \$\endgroup\$