c# - 破译连续日期范围的逻辑

标签 c# linq logic

假设我有一个 Slots 类,如下所示

public class Slots
{
   //Other properties
    .
    .
    .
    public DateTime StartTime{get;set;}
    public DateTime EndTime{ge;set;}
    //Methods
}

我有 List<Slots> , 确定连续槽组的最有效方法是什么? 连续时段定义为相对于前一个时段从第二天开始的任何一组时段,没有重叠。 如果有一天的间隔(列表中那天没有时段),那么它应该被认为是另一个时段组的开始。

public List<List<Slots>> GetSlotGroups(List<SLots> slots)
{
    //return  list of slot groups according to logic described above
}

最佳答案

这种操作最好用 GetEnumerator 来实现。 以下代码要求对列表进行排序。

IEnumerable<IEnumerable<Slot>> ToGroups(IEnumerable<Slot> slots)
{
    using (var ie = slots.GetEnumerator())
    {
        var range = new List<Slot>();
        while (ie.MoveNext())
        {
            if (range.Count > 0)
            {
                if (ie.Current.Start > range[range.Count - 1].End)
                {
                    yield return range;
                    range = new List<Slot>{ie.Current};
                    continue;
                }
            }
            range.Add(ie.Current);
        }
        yield return range;
    }
}

关于c# - 破译连续日期范围的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32830513/

相关文章:

C#,从后台线程调用匿名方法(Action<>)

c# - EntityFramework 测试初始化​​错误 : CREATE DATABASE statement not allowed within multi-statement transaction

c# - 如何从 C# 中的字符串获取枚举值?

c - 如何将数组的每个元素与同一数组的其他元素相加?

c# - 使用另一个线程修改绑定(bind)数据表时不刷新数据网格

c# - LINQ 只选择今天当前时间之后的数据

c# - 为什么在不修改枚举集合时得到 "Collection was modified; enumeration operation may not execute"?

c# - 从列表 2 中过滤列表 1

logic - 如何使用与门和或门创建与非门?

mysql - 如何编写这个 MySQL 查询?