gpt4 book ai didi

c# - 合并连续的日期期间

转载 作者:太空宇宙 更新时间:2023-11-03 15:41:07 27 4
gpt4 key购买 nike

我有一个日期周期列表,这些周期不重叠

|StartDate| EndDate|
| null | 1/12 |
| 2/12 | null |
| null | 4/12 |
| 6/12 | 8/12 |
| 9/12 | null |
| null | 10/12 |
| 11/12 | null |

我必须将这些句点组合成如下所示的列表:

|StartDate| EndDate|
| null | 1/12 |
| 2/12 | 4/12 |
| 6/12 | 8/12 |
| 9/12 | 10/12 |
| 11/12 | null |

这是我的解决方案,但我认为这不是一个聪明的方法

        var dateList = periodList.SelectMany(x => new[] { 
new {Date = x.Item1, type = "S"},
new {Date = x.Item2, type = "E"}
}).Where(x => x.Date != null).OrderBy(x => x.Date).ToArray();

var result = new List<Tuple<DateTime?, DateTime?>>();
int i = 0;
do
{
if (i == 0 && dateList[i].type == "E")
{
result.Add(new Tuple<DateTime?, DateTime?>(null, dateList[i].Date));
}
else if (i + 1 == dateList.Count() && dateList[i].type == "S")
{
result.Add(new Tuple<DateTime?, DateTime?>(dateList[i].Date, null));
}
else
{
if (dateList[i].type == "S" && dateList[i+1].type == "E")
{
result.Add(new Tuple<DateTime?, DateTime?>(dateList[i].Date, dateList[i + 1].Date));
i++;
}
}
i++;
} while (i < dateList.Count());

最佳答案

我的解决方案可能看起来更长,但它更干净在我看来。我认为你有 Period 类(而不是 Tuple<DateTime?, DateTime?> )如下:

public class Period
{
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
}

将您的日期添加到周期列表:

// Make list of periods ready
List<Period> periodList = //Prepare periods;

通过消除 null 获取开始日期和结束日期separately:

// Get start dates
List<DateTime> startDates = periodList
.Where(p => p.StartDate.HasValue)
.Select(p => p.StartDate.Value)
.ToList();

// Get end dates
List<DateTime> endDates = periodList
.Where(p => p.EndDate.HasValue)
.Select(p => p.EndDate.Value)
.ToList();

然后做其他操作:

// Clear list of periods
periodList.Clear();

// Add start dates which are bigger than LAST end date with NULL end date period
startDates.Where(s => s > endDates.Max())
.ToList()
.ForEach(s => periodList.Add(new Period() { StartDate = s, EndDate = null }));

// Add end dates which are smaller than FIRST start date with NULL start date period
endDates.Where(e => e < startDates.Min())
.ToList()
.ForEach(e => periodList.Add(new Period() {StartDate = null, EndDate = e}));

// Match other dates and add them to list
startDates.Where(s => s < endDates.Max())
.ToList()
.ForEach(s => periodList.Add(new Period()
{
StartDate = s,
EndDate = endDates.Where(e => e > s).Min()
}));

// Oder period list
periodList = periodList.OrderBy(p => p.StartDate).ToList();

您可以测试 .NET Fiddle 演示 here .

希望对您有所帮助。

关于c# - 合并连续的日期期间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30229368/

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