我有一个日期列表,我想按连续几天的项目分组
因此,如果在列表中我有以下日期:
2013年12月31日
2014年1月1日2014年
1月2日2014年
2月1日2014年
2月2日2014年
2月16日2014年
3月13日
我想提出一种将其分组的方法,这样我得到:
组1:
2013年12月31日
2014年
1月1日2014年1月2日
组2:
2014年
2月1日,2014年2月2日
组3:
2014年2月16日
组4:2014年3月13日
如您所见,分组基于连续几天的项目。
在C#中,最好的方法是获取此列表并将其转换为这些组?
以下代码的逻辑很简单,对列表进行排序并检查天数增量是否大于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;
}
并输出:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句