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?
dates.GroupBy(d => d).ToDictionary(g => g.Key, g => g.Count());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With