c# 一个关于时间截断的算法取巧

场景如下:

在某一段时间内(有规律,以一个星期为最大区间),从一个时间区间中排除另外一个或者多个时间区间后,返回时间区间集合。

举例如下:

//时间区间:2018-02-01~2018-02-07
//待排除时间区间集合:2018-02-03~2018-02-04,2018-02-06~2018-02-06   

设计算法如下:

public class myclass
{
    public DateTime BeginDate { get; set; }

    public DateTime EndDate { get; set; }

    public List<myclass> SpCalc(List<myclass> list)
    {
        int Cnt = (EndDate - BeginDate).Days + 1;
        bool[] _temp = new bool[Cnt];
        Action<int, int, bool> _calc = (bIndex, eIndex, v) =>
            {
                for (int i = bIndex; i <= eIndex; i++)
                {
                    _temp[i] = v;
                }
            };
        //初始化,全部置为true
        _calc(0, Cnt, true);
        //需要排除的时间段全部置为false
        list.ForEach(q => _calc((q.BeginDate - BeginDate).Days, (q.EndDate - BeginDate).Days, false));
        var resList = new List<myclass>();
        //遍历获取有效时间段
        int index = 0, start = -1;
        while (index < Cnt)
        {
            if (_temp[index])
            {
                if (start == -1)
                    start = index;
                if (index == 6)
                    resList.Add(new myclass()
                    {
                        BeginDate = BeginDate.AddDays(start),
                        EndDate = BeginDate.AddDays(index)
                    });
            }
            else
            {
                if (start != -1)
                    resList.Add(new my()
                    {
                        BeginDate = BeginDate.AddDays(start),
                        EndDate = BeginDate.AddDays(index - 1)
                    });
                start = -1;
            }
            index++;
        }
        return resList;
    }
}
原文地址:https://www.cnblogs.com/lcawen/p/8663400.html