C # Best practice - counting the number of times each date occurs

I am looking for best practice to count how many times each date appears in a list.

At the moment, I have working code (just tested), but I think the way I did is not so good.

var dates = new List<DateTime>(); //Fill list here var dateCounter = new Dictionary<DateTime, int>(); foreach (var dateTime in dates) { if (dateCounter.ContainsKey(dateTime)) { //Increase count dateCounter[dateTime] = dateCounter[dateTime] + 1; } else { //Add to dictionary dateCounter.Add(dateTime, 1); } } 

Who knows the best solution?

+6
source share
1 answer
 dates.GroupBy(d => d).ToDictionary(g => g.Key, g => g.Count()); 
+9
source

Source: https://habr.com/ru/post/951128/


All Articles