[英]C# Check datetime list whether contains linked dates and convert to string
我想实现一个 function 有点像将链接日期转换为字符串,可以参考以下代码:
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
我想要一个 output ,例如: 01 Jan 2021 to 03 Jan 2021, 09 Jan 2021 to 10 Jan 2021, 15 Jan 2021
。
有没有什么方法/库可以用来完成这个function?
有几种方法可以对连续的日期进行分组。 这只是一个示例,如果您不想调用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));
Output
01 Jan 2021 to 03 Jan 2021, 09 Jan 2021 to 10 Jan 2021, 15 Jan 2021
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.