既然你要確定連續日期範圍的範圍,我認爲你唯一的選擇是,像你說的一環。您可以在單次做到這一點,雖然,並把它放在一個擴展方法,以便它會在任何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