c# - C#检查日期时间列表是否包含链接日期并转换为字符串
问题描述
我想实现一个函数,比如将链接日期转换为字符串,可以参考以下代码:
List<DateTime> dateList = new List<DateTime>();
dateList.Add(DateTime.Parse("01012021")); // 01 Jan 2021
dateList.Add(DateTime.Parse("02012021")); // 02 Jan 2021
dateList.Add(DateTime.Parse("03012021")); // 03 Jan 2021
dateList.Add(DateTime.Parse("09012021")); // 09 Jan 2021
dateList.Add(DateTime.Parse("10012021")); // 10 Jan 2021
dateList.Add(DateTime.Parse("15012021")); // 15 Jan 2021
我想要一个像这样的输出:01 Jan 2021 to 03 Jan 2021, 09 Jan 2021 to 10 Jan 2021, 15 Jan 2021
.
有什么方法/库可以用来完成这个功能吗?
解决方案
有几种方法可以对连续的日期进行分组。这只是一个示例,如果您不想调用,可能会有更有效的方法Last
。
给定
public static IEnumerable<DateTime[]> GetSequential(IEnumerable<DateTime> source)
{
var temp = new List<DateTime>();
foreach (var current in source)
{
if (temp.Count == 0 || temp.Last().AddDays(1).Date == current.Date)
{
temp.Add(current);
continue;
}
yield return temp.ToArray();
temp.Clear();
temp.Add(current);
}
if(temp.Any())
yield return temp.ToArray();
}
用法
var list = new[]
{
DateTime.ParseExact("01012021", "ddMMyyyy", CultureInfo.InvariantCulture),
DateTime.ParseExact("02012021", "ddMMyyyy", CultureInfo.InvariantCulture),
DateTime.ParseExact("03012021", "ddMMyyyy", CultureInfo.InvariantCulture),
DateTime.ParseExact("09012021", "ddMMyyyy", CultureInfo.InvariantCulture),
DateTime.ParseExact("10012021", "ddMMyyyy", CultureInfo.InvariantCulture),
DateTime.ParseExact("15012021", "ddMMyyyy", CultureInfo.InvariantCulture)
};
var results = GetSequential(list)
.Select(x => x.Count() == 1 ? $"{x.First():dd MMM yyyy}" : $"{x.First():dd MMM yyyy} to {x.Last():dd MMM yyyy}");
Console.WriteLine(string.Join(", ", results));
输出
01 Jan 2021 to 03 Jan 2021, 09 Jan 2021 to 10 Jan 2021, 15 Jan 2021
推荐阅读
- dataframe - 在“无类型”对象上转换 pyspark 数据帧失败
- github - Get number of stargazers at a certain point in time?
- angular - How to enable vertical scroll when more data is loaded in the sub component in form of gridcontrols?
- html - 如何更改django中的默认注册
- python-3.x - 用于命名实体识别的 Spacy 交叉验证
- c# - 为什么 ComputeHash 的执行速度比 certutil -hashfile 慢得多?
- perl - MULTIPLICITY 和 PERL_IMPLICIT_CONTEXT 的关系
- javascript - Wordpress - 如何从优化 JavaScript 代码中排除 google autoaddress js
- pdf - 在 Illustrator 中链接时在 windows 下使用 ggsave 生成 PDF 字体的问题
- microsoft-graph-api - 如何使用 Graph API 获取扩展属性?