Kjell Derous
Kjell Derous

Reputation: 522

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?

Upvotes: 6

Views: 190

Answers (1)

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22794

dates.GroupBy(d => d).ToDictionary(g => g.Key, g => g.Count());

Upvotes: 9

Related Questions