我有一组KeyValuePair项目,其中DateTime为键,字符串为value。 基本上我的数据看起来像:
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
我想列出我每天有多少项(不同)。因此查询将导致:
12/07/2013 - 4
13/07/2013 - 2
14/07/2013 - 1
答案 0 :(得分:17)
使用group by
var dateGrouped = dates.GroupBy(x => x.Key)
.Select(x => new { Date = x.Key, Values = x.Distinct().Count() });
答案 1 :(得分:2)
以下是完整示例的解决方案
var list = new[]
{
new {Date = new DateTime(2013,07,12), value = 10220},
new {Date = new DateTime(2013,07,12), value = 10220},
new {Date = new DateTime(2013,07,12), value = 12220},
new {Date = new DateTime(2013,07,12), value = 11240},
new {Date = new DateTime(2013,07,12), value = 15220},
new {Date = new DateTime(2013,07,13), value = 23220},
new {Date = new DateTime(2013,07,13), value = 35620},
new {Date = new DateTime(2013,07,14), value = 15620},
new {Date = new DateTime(2013,07,14), value = 15620},
};
var res = from l in list group l by new { l.Date } into g select new { g.Key.Date, value = g.Distinct().Count() };
foreach (var item in res)
{
Console.WriteLine(item.Date + " " + item.value);
}