查找日期时间列表中的不连续性,c#, LINQ
本文关键字:不连续性 LINQ 日期 时间 列表 查找 | 更新日期: 2023-09-27 18:03:17
该算法基于查找DateTime列表中缺失的日期,如果它们间隔一秒或有其他时间间隔,则对日期块进行分组
DateTime startDate = DateTime.Now;
Random rnd = new Random();
List<DateTime> datesList = new List<DateTime>();
List<List<DateTime>> segregatedList = new List<List<DateTime>>();
var oneYear = 60*60*24*365;
///////////////////// INPUT GENERATE /////////////////////
for (var i = 0; i < oneYear; ++i)
{
if (rnd.Next(1, 5) == 4) continue;
datesList.Add(startDate.AddSeconds(i));
}
/////////////////////// ALGORITHM ///////////////////////
segregatedList.Add(new List<DateTime>());
var difference = datesList[1] - datesList[0];
var j = 0;
var lastIndex = datesList.Count - 1;
for (var i = 0; i < datesList.Count; ++i)
{
segregatedList[j].Add(datesList[i]);
if (i == lastIndex) continue;
if ((datesList[i + 1] - datesList[i]) == difference)
{
difference = datesList[i + 1] - datesList[i];
continue;
}
segregatedList.Add(new List<DateTime>());
++j;
}
我想知道是否有能力在LINQ中编写这段代码。
如果我假设你实际上只是想按日期/时间分组,那么这是LINQ版本:
DateTime startDate = DateTime.Now;
Random rnd = new Random();
var oneYear = 60*60*24*365;
List<DateTime> datesList =
Enumerable
.Range(0, oneYear)
.Where(i => rnd.Next(1, 5) != 4)
.Select(i => startDate.AddSeconds(i))
.ToList();
List<List<DateTime>> segregatedList =
datesList
.Skip(1)
.Aggregate(
datesList
.Take(1)
.Select(x => new List<DateTime>() { x })
.ToList(),
(a, x) =>
{
if (x.Subtract(a.Last().Last()) == TimeSpan.FromSeconds(1.0))
{
a.Last().Add(x);
}
else
{
a.Add(new List<DateTime>() { x });
}
return a;
});