Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Best practice - Counting how many times each date occurs

I'm looking for a best practice for counting how many times each date occurs in a list.

For now, 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);
   }
}

Anyone who knows a better solution?

like image 501
Kjell Derous Avatar asked Aug 06 '13 12:08

Kjell Derous


1 Answers

dates.GroupBy(d => d).ToDictionary(g => g.Key, g => g.Count());
like image 177
It'sNotALie. Avatar answered Oct 05 '22 22:10

It'sNotALie.