Reputation: 522
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
Reputation: 22794
dates.GroupBy(d => d).ToDictionary(g => g.Key, g => g.Count());
Upvotes: 9