既然你要确定连续日期范围的范围,我认为你唯一的选择是,像你说的一环。您可以在单次做到这一点,虽然,并把它放在一个扩展方法,以便它会在任何IList<DateTime>
操作,例如:
// purely an example, chances are this will have actual, y'know logic in live
public class DateRange
{
private List<DateTime> dates = new List<DateTime>();
public void Add(DateTime date)
{
this.dates.Add(date);
}
public IEnumerable<DateTime> Dates
{
get { return this.dates; }
}
}
public static IEnumerable<DateRange> GetRanges(this IList<DateTime> dates)
{
List<DateRange> ranges = new List<DateRange>();
DateRange currentRange = null;
// this presumes a list of dates ordered by day, if not then the list will need sorting first
for(int i = 0; i < dates.Count; ++i)
{
var currentDate = dates[i];
if(i == 0 || dates[i - 1] != currentDate.AddDays(-1))
{
// it's either the first date or the current date isn't consecutive to the previous so a new range is needed
currentRange = new DateRange();
ranges.Add(currentRange);
}
currentRange.Add(currentDate);
}
return ranges;
}
你也可以将它通过传递一个IEnumerable<DateTime>
更加通用:
public static IEnumerable<DateRange> GetRanges(this IEnumerable<DateTime> dates)
{
List<DateRange> ranges = new List<DateRange>();
DateRange currentRange = null;
DateTime? previousDate = null;
// this presumes a list of dates ordered by day, if not then the list will need sorting first
foreach(var currentDate in dates)
{
if(previousDate == null || previousDate.Value != currentDate.AddDays(-1))
{
// it's either the first date or the current date isn't consecutive to the previous so a new range is needed
currentRange = new DateRange();
ranges.Add(currentRange);
}
currentRange.Add(currentDate);
previousDate = currentDate;
}
return ranges;
}
这些日期的地区是什么? “01/02/10”可能是2010年2月1日或2010年1月1日(甚至可能是2001年2月10日?),具体取决于它们代表的区域设置。因为我们正在谈论范围和排序,这有所作为。 – 2010-08-25 08:44:42
他们是英国的格式;) – 2010-08-25 08:48:37
它可能只是咖啡不足,但我不能推断从这些日期生产这些范围的规则。你能澄清吗? – AakashM 2010-08-25 08:52:32