簡體   English   中英

C# 檢查日期時間列表是否包含鏈接日期並轉換為字符串

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM