解决方案 »

  1.   


    static void Main()
    {
        TimeRange workHours = new TimeRange(TimeSpan.FromHours(8), TimeSpan.FromHours(20));
        List<TimeRange> exceptions = new List<TimeRange>()
        {
            new TimeRange(TimeSpan.FromHours(00.00), TimeSpan.FromHours(08.50)),
            new TimeRange(TimeSpan.FromHours(11.50), TimeSpan.FromHours(13.00)),
            new TimeRange(TimeSpan.FromHours(17.00), TimeSpan.FromHours(19.00)),
        };
        var ranges = GetEffectiveWorkHours(workHours, exceptions);
        var hours = ranges.Sum(r => (r.End - r.Start).TotalHours); //8小时 
        //(12小时,减去: 早上半小时,中午一个半,傍晚两小时)
    }struct TimeRange
    {
        public TimeRange(TimeSpan s, TimeSpan e)
        {
            this.Start = s; this.End = e;
        }
        public TimeSpan Start;
        public TimeSpan End;
    }static List<TimeRange> GetEffectiveWorkHours(TimeRange workHours, List<TimeRange> exceptions)
    {
        List<TimeRange> result = new List<TimeRange>(){workHours};
        foreach (var exception in exceptions)
        {
            List<TimeRange> outputs = new List<TimeRange>();
            foreach (var range in result)
            {
                if (range.Start <= exception.End && range.End >= exception.Start)
                {
                    if (range.Start < exception.Start)
                    {
                        outputs.Add(new TimeRange(range.Start, exception.Start));
                    }
                    if (range.End > exception.End)
                    {
                        outputs.Add(new TimeRange(exception.End, range.End));
                    }
                }
                else
                {
                    outputs.Add(range);
                }
            }
            result = outputs;
        }
        return result;
    }