在 List<DateTime> 中查找缺失的日期并将该日期插入到正确的索引中

fjo*_*pen 1 .net c# foreach datetime for-loop

假设我有一个包含以下日期的列表。

List<DateTime> dateList = new List<DateTime>();
dateList.Add(new DateTime(2002, 01, 01));
dateList.Add(new DateTime(2002, 01, 02));
dateList.Add(new DateTime(2002, 01, 03));
dateList.Add(new DateTime(2002, 01, 04));
dateList.Add(new DateTime(2002, 01, 06));
dateList.Add(new DateTime(2002, 01, 08));
Run Code Online (Sandbox Code Playgroud)

如何遍历 dateList,找到缺失的 DateTimes(2002-01-05 和 2002-01-07),然后创建这些 DateTimes 并将它们添加到 dateList 的正确索引上?

Tim*_*ter 5

您可以使用以下方法来确定最小和最大日期以及时间跨度差异,然后生成列表:

DateTime min = dateList.Min();
DateTime max = dateList.Max();
TimeSpan diff = max - min;
dateList = Enumerable.Range(0, diff.Days + 1).Select(d => min.AddDays(d)).ToList();
Run Code Online (Sandbox Code Playgroud)

您需要使用diff.Days + 1来包含结束日期。

如果由于某种原因无法使用 LINQ,则可以使用 for 循环 and List.Insert,但List.Sort如果不确定列表是否已排序,则必须事先使用:

dateList.Sort();
if (dateList.Count > 1)
{
    for (int i = 0; i < dateList.Count - 1; i++)
    {
        DateTime currrent = dateList[i].Date;
        DateTime next = dateList[i + 1].Date;
        DateTime expected = currrent.AddDays(1);
        if (next != expected)
        {
            dateList.Insert(++i, expected);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您会看到 LINQ 版本的可读性如何。