简体   繁体   中英

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:

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 .

Is there any way/library can be used to complete this 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 .

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

01 Jan 2021 to 03 Jan 2021, 09 Jan 2021 to 10 Jan 2021, 15 Jan 2021

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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