在时间跨度列表中找到时间跨度之间的最大持续时间

我已编写此代码来查找有序时间跨度之间的最大时间跨度。它工作正常,但是是否有更有效的方法来完成此操作,如果列表中有很多项目,这可能会变得很慢?

var events = this.Events.OrderBy(x => x.TimeSinceStart).ToList();

var largestTime = events.FirstOrDefault().TimeSinceStart;

for(int i = 0; i < events.Count() - 1; i ++)
{
    var difference = events[i + 1].TimeSinceStart - events[i].TimeSinceStart;

    if (difference > largestTime)
        largestTime = difference;
}
评论
囚心锁
囚心锁

You can try to use Zip method for that

var events = this.Events.OrderBy(x => x.TimeSinceStart);

var largestTime = events
    .Zip(events.Skip(1), (x, y) => y.TimeSinceStart - x.TimeSinceStart)
    .Max();

But you still need go though all the sequence, with O(n) complexity. But in your case the most complexity is spend to OrderBy, sorting algorithms usually have O(nlog(n)) complexity

点赞
评论
祝玛丽
祝玛丽

Use Ticks for better performance:

var events = this.Events.Select(x => x.TimeSinceStart.Ticks).OrderBy(x => x).ToList();

var largestTime = events.FirstOrDefault();

for (int i = 0; i < events.Count() - 1; i++)
{
    var difference = events[i + 1].TimeSinceStart - events[i].TimeSinceStart;

    if (difference > largestTime)
        largestTime = difference;
}
var maxGap = TimeSpan.FromTicks(largestTime);
点赞
评论