Chillidad
Chillidad

Reputation: 1

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?

Upvotes: 0

Views: 42

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

You have to define what is the best approach in you case (fasest, most readable etc.). You can try, for instance, 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));

Outcome:

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

Upvotes: 2

Related Questions