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#中,将连续日期分组到列表中的最佳方式是什么?
基础教程推荐
猜你喜欢
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
