Home > Mobile >  LINQ query for DateTime ranges overlapping in collection items
LINQ query for DateTime ranges overlapping in collection items

Time:11-16

In the following case, the method CanUnloadAll checks if there are no overlap in the unloading times, considering all trucks.

The current scenario, should returns TRUE but it is returning FALSE.

What's wrong with the logic in the LINQ query?

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));
    }
}

To make it easier, I am using .NET Fiddle.

https://dotnetfiddle.net/Mis663

Regards

Solution:

    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;
    }

CodePudding user response:

You are using the DateTime.Date property, which is the date component without the time part. You must use the DateTime:

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