我想在List中找到缺少的时间范围。 事件有StartDate和EndDate(随时间)。我将在该列表中具有相同的日/月/年,因此每个对象中只有不同的时间。假设每个事件都在01-01-2016,那么时间就是这样:
我想在该列表中找到空闲时间,所以我想得到类似的东西
我怎么能得到类似的东西?
答案 0 :(得分:1)
尝试以下方法,假设时间顺序
var today = DateTime.UtcNow;
var bookedTimes = new[]
{
new DateRange(new DateTime(today.Year, today.Month, today.Day, 07, 00, 00),
new DateTime(today.Year, today.Month, today.Day, 09, 00, 00)),
new DateRange(new DateTime(today.Year, today.Month, today.Day, 09, 00, 00),
new DateTime(today.Year, today.Month, today.Day, 11, 00, 00)),
new DateRange(new DateTime(today.Year, today.Month, today.Day, 13, 00, 00),
new DateTime(today.Year, today.Month, today.Day, 14, 00, 00)),
new DateRange(new DateTime(today.Year, today.Month, today.Day, 18, 00, 00),
new DateTime(today.Year, today.Month, today.Day, 20, 00, 00)),
};
var freeTimes = new List<DateRange>();
for (var i = 0; i < bookedTimes.Length -1; i++)
{
var current = bookedTimes[i];
var next = bookedTimes[i + 1];
if (current.To != next.From)
{
var range = new DateRange(current.To, next.From);
freeTimes.Add(range);
}
}
foreach (var time in freeTimes)
{
Console.WriteLine($"From {time.From.ToShortTimeString()}, to: {time.To.ToShortTimeString()}");
}
// Outputs:
// From 11:00, to: 13:00
// From 14:00, to: 18:00
答案 1 :(得分:0)
您还可以使用Linq Zip方法将列表加入到自身1条目中,创建一个间隙列表&amp;然后过滤出开始和放大的条目。结束时间是一样的。
var gaplist =
eventlist.Zip(eventlist.Skip(1), (ev1, ev2) => new MyEvent(ev1.End, ev1.Start))
.Where(gp => gp.Start != gp.End)
.ToList();