gpt4 book ai didi

c# - 如果日期相差一天,则合并列表元素

转载 作者:行者123 更新时间:2023-12-04 07:21:06 25 4
gpt4 key购买 nike

我有一个看起来像这样的列表。如果日期相隔 1 天(“2022, 01, 01”和“2022, 01, 02),我需要合并此列表元素,它们的费率、roomTypeId 和 Accessibility 完全相同。DateFrom 和 DateTo 始终相同在我给出的列表中,每个可用性代表一天。

             new Availability
{
Accessibility = 1,
RoomTypeId = "12345",
Rate = 50,
DateFrom = new DateTime(2022, 01, 01),
DateTo = new DateTime(2022, 01, 01)
},
new Availability
{
Accessibility = 1,
RoomTypeId = "12345",
Rate = 50,
DateFrom = new DateTime(2022, 01, 02),
DateTo = new DateTime(2022, 01, 02)
},
new Availability
{
Accessibility = 1,
RoomTypeId = "12345",
Rate = 100,
DateFrom = new DateTime(2022, 01, 04),
DateTo = new DateTime(2022, 01, 04)
},
new Availability
{
Accessibility = 6,
RoomTypeId = "12345",
Rate = 100,
DateFrom = new DateTime(2022, 01, 05),
DateTo = new DateTime(2022, 01, 05)
},
new Availability
{
Accessibility = 6,
RoomTypeId = "12345",
Rate = 100,
DateFrom = new DateTime(2022, 01, 6),
DateTo = new DateTime(2022, 01, 06)
},
结果应如下所示:
             new Availability
{
Accessibility = 1,
RoomTypeId = "12345",
Rate = 50,
DateFrom = new DateTime(2022, 01, 01),
DateTo = new DateTime(2022, 01, 02)
},
new Availability
{
Accessibility = 1,
RoomTypeId = "12345",
Rate = 100,
DateFrom = new DateTime(2022, 01, 04), <- missing (2002, 01, 03) so it should crate a new group
DateTo = new DateTime(2022, 01, 04)
},
new Availability
{
Accessibility = 6, <- different
RoomTypeId = "12345",
Rate = 100,
DateFrom = new DateTime(2022, 01, 05),
DateTo = new DateTime(2022, 01, 06)
}
我怎样才能以最佳方式做到这一点?我尝试按 RoomTypeId 对列表进行分组,按日期排序并将日期与以前的元素进行比较,但还不是这样。

最佳答案

这有点脏,但可以提供帮助!您可以跳过不感兴趣的元素,同时保留一些标志元素。而且它只是一个枚举,所以 O(n) 复杂度

public static IEnumerable<Availability> GetMerged(List<Availability> oldList)
{
var oldValue = oldList[0];
foreach (var currentValue in oldList)
{
if (IsDifferent(oldValue, currentValue))
{
yield return oldValue;
oldValue = currentValue;
}
}

yield return oldValue;
}

public static bool IsDifferent(Availability x, Availability y)
{
if (x.Accessibility != y.Accessibility || x.Rate != y.Rate || x.RoomTypeId != y.RoomTypeId)
return true;
if (Math.Abs((x.DateFrom - x.DateTo).TotalDays) > 1)
return true;

return false;
}
您也可以通过 LINQ 组按方法和覆盖自定义比较器,但您应该选择正确的自定义 GetHashCode 函数,我发现现在很难。

关于c# - 如果日期相差一天,则合并列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68495441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com