In C#, what is the best way to group consecutive dates in a list?(在C#中,将连续日期分组到列表中的最佳方式是什么?)
本文介绍了在C#中,将连续日期分组到列表中的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个日期列表,我想按连续日期的项目分组
因此,如果列表中有以下日期:
2013年12月31日
2014年1月1日
2014年1月2日
2014年2月1日
2014年2月2日
2014年2月16日
2014年3月13日
我想想出一种方法来对此进行分组,这样我就可以:
第一组:
2013年12月31日
2014年1月1日
2014年1月2日
第二组:
2014年2月1日
2014年2月2日
第三组:
2014年2月16日
如您所见,分组基于连续天数的项目。
在C#中,获取此列表并将其转换为这些组的最佳方式是什么?
推荐答案
以下代码的逻辑非常简单,对列表进行排序并检查天数增量是否大于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;
}
和输出:
这篇关于在C#中,将连续日期分组到列表中的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:在C#中,将连续日期分组到列表中的最佳方式是什么?
基础教程推荐
猜你喜欢
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 如果条件可以为空 2022-01-01
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
