查找DateTime列表中的不连续性,C#,LINQ

时间:2016-08-22 06:02:05

标签: c# linq datetime

该算法基于在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中编写这段代码。

1 个答案:

答案 0 :(得分:0)

如果我假设您实际上只想按日期/时间分组,那么这是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;
                });