在以下情況下,方法CanUnloadAll檢查卸載時間是否沒有重疊,考慮所有卡車。
當前方案應該回傳 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;
}
uj5u.com熱心網友回復:
您正在使用該DateTime.Date屬性,它是沒有時間部分的日期組件。您必須使用DateTime:
bool flag = TruckA.Start >= TruckB.End || TruckB.Start >= TruckA.End
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/357910.html
上一篇:通過輸入更改月、年或日
