首页 > 解决方案 > Create list of months reoccurrence to be used in timeline chart

问题描述

I have a list dates in C# and I want to create a list of (Month, Count).

Example:

01/01/2021
05/01/2021
10/03/2021

etc..

Expected List will be:

January,2
February,0
March,1

What is the best approach?

标签: c#listdatetime

解决方案


您必须定义在您的情况下最好的方法是什么(最快、最易读等)。例如,您可以尝试Linq ( GroupJoin ):

  using System.Globalization;
  using System.Linq;

  ...

  // Given list of dates...
  List<DateTime> dates = new List<DateTime>() {
    new DateTime(2021, 1, 1),
    new DateTime(2021, 1, 5),
    new DateTime(2021, 3, 10),
  };

  ... 

  // ... we query it with a help of Ling GroupJoin
  var result = Enumerable
    .Range(1, 12)
    .GroupJoin(dates, 
               index => index, 
               date => date.Month, 
               (index, src) => $"{CultureInfo.CurrentCulture.DateTimeFormat.MonthNames[index - 1]},{src.Count()}")
    .ToList();

  // Let's have a look
  Console.WriteLine(string.Join(Environment.NewLine, result));

结果:

January,2
February,0
March,1
April,0
May,0
June,0
July,0
August,0
September,0
October,0
November,0
December,0

推荐阅读