以下是我會做的:
static IEnumerable<DateTime> GetMissingMonths(IEnumerable<DateTime> currentDates, DateTime startDate, DateTime endDate)
{
var yearMonths = new HashSet<Tuple<int, int>>(currentDates.Select(d => Tuple.Create(d.Year, d.Month)));
DateTime current = new DateTime(startDate.Year, startDate.Month, 1);
if (current < startDate)
current = current.AddMonths(1);
while (current <= endDate)
{
if (!yearMonths.Contains(Tuple.Create(current.Year, current.Month)))
{
yield return current;
}
current = current.AddMonths(1);
}
}
編輯:如果你不能使用元組,你可以使用匿名類型來代替,用一個輔助方法來創建的HashSet:
static IEnumerable<DateTime> GetMissingMonths(IEnumerable<DateTime> currentDates, DateTime startDate, DateTime endDate)
{
var yearMonths = MakeHashSet(currentDates.Select(d => new { d.Year, d.Month }));
DateTime current = new DateTime(startDate.Year, startDate.Month, 1);
if (current < startDate)
current = current.AddMonths(1);
while (current <= endDate)
{
if (!yearMonths.Contains(new { current.Year, current.Month }))
{
yield return current;
}
current = current.AddMonths(1);
}
}
static HashSet<T> MakeHashSet<T>(IEnumerable<T> source)
{
return new HashSet<T>(source);
}
的MakeHashSet
方法可以讓你當T是匿名類型時,使用類型推斷來創建HashSet<T>
。
當你說「月」時,它是否包括年?您的描述中是2010年1月和2011年1月的不同月份嗎? – 2011-01-14 13:05:39
你可以舉個例子嗎? – Pabuc 2011-01-14 13:05:49
如果您將startDate指定爲1月15日,是否應包含1月份?既然你指定你想要那個月的第一個。 – 2011-01-14 14:13:41