DateTime minStart = timeList.Min(l => l.StartTime);
DateTime maxEnd = timeList.Max(l => l.EndTime);
TimeSpan duration = maxEnd - minStart;
EndTime
属性:public DateTime EndTime
{
get { return this.StartTime.Add(this.Duration); }
}
这将获取约会的总持续时间,并不考虑约会之间有时间间隔的情况。您需要先将列表处理成子列表,其中约会重叠或是连续的。可以使用以下伪代码:
var orderedAppointments = appointments.OrderBy(a => a.StartTime);
foreach (var appointment in orderedAppointments)
{
if (first appointment)
add to new sub list and add sub list to list of lists
else if (appointment.StartTime <= subList.Max(s => s.EndTime))
add to existing sub list
else
add to new sub list and add sub list to list of lists
}
一个简单但效率低下的算法(O(n²)
),不需要排序列表。
首先,所有重叠的区间被合并,然后区间长度被加总(向下滚动):
struct TimeRange
{
DateTime Start;
DateTime End;
public TimeRange(DateTime start, DateTime end)
{
Start = start;
End = end;
}
public TimeSpan Duration
{
get
{
return End-Start;
}
}
public static bool Overlap(TimeRange tr1, TimeRange tr2)
{
return (tr2.Start <= tr1.End && tr1.Start <= tr2.End);
}
public static TimeRange Merge(TimeRange tr1, TimeRange tr2)
{
return new TimeSpan(
(tr1.Start < tr2.Start) ? tr1.Start : tr2.Start,
(tr1.End > tr2.End) ? tr1.End : tr2.End
);
}
}
List<TimeRange> timeRanges; // A *copy* of your data list
for(int i = 0; i < timeRanges.Count; i++)
{
for(int j = i+1; j < timeRanges.Count; j++)
{
if(TimeRange.Overlap(timeRanges[i],timeRanges[j])
{
timeRanges[i] = TimeRange.Merge(timeRanges[i],timeRanges[j]);
timeRanges.RemoveAt(j);
j--;
}
}
}
TimeSpan totalDuration = TimeSpan.Zero;
foreach(TimeRange in timeRanges)
{
totalDuration += timeRanges.Duration;
}