首页 > 解决方案 > 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.

有什么方法/库可以用来完成这个功能吗?

标签: c#linqdatetime

解决方案


有几种方法可以对连续的日期进行分组。这只是一个示例,如果您不想调用,可能会有更有效的方法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

推荐阅读