LINQ 查询集合项中重叠的日期时间范围

LINQ query for DateTime ranges overlapping in collection items

在以下情况下,CanUnloadAll 方法会检查卸载时间是否没有重叠,考虑到所有卡车。

当前情况应该returns TRUE 但它返回 FALSE。

LINQ 查询中的逻辑有什么问题?

using System;
using System.Collections.Generic;
using System.Linq;

public class UnloadingTime
{
    public DateTime Start { get; private set; }
    public DateTime End { get; private set; }

    public UnloadingTime(DateTime start, DateTime end)
    {
        this.Start = start;
        this.End = end;
    }
}

public static class UnloadingTrucks
{
    public static bool CanUnloadAll(IEnumerable<UnloadingTime> unloadingTimes)
    {
        return unloadingTimes.Any(
                TruckA => unloadingTimes.Any(
                    TruckB => TruckB != TruckA &&
                           !((
                               TruckA.Start.Date >= TruckB.End.Date || 
                               TruckB.Start.Date >= TruckA.End.Date
                            ))
                ));
    }

    public static void Main(string[] args)
    {
        var format = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat;

        UnloadingTime[] unloadingTimes = new UnloadingTime[] 
        {
            new UnloadingTime(DateTime.Parse("3/4/2019 19:00", format), DateTime.Parse("3/4/2019 20:30", format)),
            new UnloadingTime(DateTime.Parse("3/4/2019 22:10", format), DateTime.Parse("3/4/2019 22:30", format)),
            new UnloadingTime(DateTime.Parse("3/4/2019 22:40", format), DateTime.Parse("3/4/2019 23:00", format))
        };

        Console.WriteLine(UnloadingTrucks.CanUnloadAll(unloadingTimes));
    }
}

为了方便起见,我正在使用 .NET Fiddle。

https://dotnetfiddle.net/Mis663

此致

解决方案:

    public static bool CanUnloadAll(IEnumerable<UnloadingTime> unloadingTimes)
    {
        bool hasOverlap = unloadingTimes.Any(
                TruckA => unloadingTimes.Any(
                    TruckB => TruckB != TruckA &&
                           !((
                               TruckA.Start >= TruckB.End || 
                               TruckB.Start >= TruckA.End
                            ))
                ));
        
        return !hasOverlap;
    }

您正在使用 DateTime.Date 属性,这是没有时间部分的日期部分。您必须使用 DateTime:

bool flag = TruckA.Start >= TruckB.End || TruckB.Start >= TruckA.End