以下是我会做的:
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