简体   繁体   English

C# 检查日期时间列表是否包含链接日期并转换为字符串

[英]C# Check datetime list whether contains linked dates and convert to string

I would like to implement a function somehow like converting the linked dates into string, can refer to the following codes:我想实现一个 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

And I want a output like: 01 Jan 2021 to 03 Jan 2021, 09 Jan 2021 to 10 Jan 2021, 15 Jan 2021 .我想要一个 output ,例如: 01 Jan 2021 to 03 Jan 2021, 09 Jan 2021 to 10 Jan 2021, 15 Jan 2021

Is there any way/library can be used to complete this function?有没有什么方法/库可以用来完成这个function?

There are several ways you can group sequential days.有几种方法可以对连续的日期进行分组。 This is just one example, there are likely more efficient approaches if you didn't want invoke Last .这只是一个示例,如果您不想调用Last ,可能会有更有效的方法。

Given给定

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();
}

Usage用法

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 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM