且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中,将连续日期分组到列表中的***方式是什么?

更新时间:2022-01-23 16:56:13

以下代码的逻辑非常简单,对列表进行排序并检查天数增量是否大于1,如果大于1,则为其创建一个新组:

创建测试日期:

//Dates for testing
 List<DateTime> dates = new List<DateTime>()
 { 
      new DateTime(2013,12,31),
      new DateTime(2014,2,2),
     new DateTime(2014,1,1),
     new DateTime(2014,1,2),
     new DateTime(2014,2,1),               
     new DateTime(2014,2,16),
     new DateTime(2014,3,13),
 };

并创建组:

 dates.Sort();
 //this will hold the resulted groups
 var groups = new List<List<DateTime>>();
 // the group for the first element
 var group1 = new List<DateTime>(){dates[0]};
 groups.Add(group1);

 DateTime lastDate = dates[0];
 for (int i = 1; i < dates.Count; i++)
 {
     DateTime currDate = dates[i];
     TimeSpan timeDiff = currDate - lastDate;
     //should we create a new group?
     bool isNewGroup = timeDiff.Days > 1;
     if (isNewGroup)
     {
         groups.Add(new List<DateTime>());
     }
     groups.Last().Add(currDate);
     lastDate = currDate;
 }

和输出: