C# LINQ counting elements with DISTINCT

Ras picture Ras · Jul 15, 2013 · Viewed 18.4k times · Source

I have a collection of KeyValuePair items with DateTime as key and a string as value. Basically my data looks like:

12/07/2013 - 10220
12/07/2013 - 10220
12/07/2013 - 12220
12/07/2013 - 11240
12/07/2013 - 15220
13/07/2013 - 23220
13/07/2013 - 35620
14/07/2013 - 15620
14/07/2013 - 15620

I would like to have a List of how many items (distinct) I've for each days. So the query would result in a:

12/07/2013 - 4
13/07/2013 - 2
14/07/2013 - 1

Answer

gzaxx picture gzaxx · Jul 15, 2013

use group by

var dateGrouped = dates.GroupBy(x => x.Key)
                       .Select(x => new { Date = x.Key, Values = x.Distinct().Count() });