计算db table asp.net linq中每个月的出现次数

时间:2015-06-17 08:16:11

标签: c# asp.net linq sql-server-2008

我有一张包含date col的表格。

我想使用LINQ查询并计算每月的发生次数,并将其显示为month, occurrence of month in the table

1=2(1 is month, 2 is number of occurrence),2=5,3=12等等使用asp.net。

有人可以告诉我该怎么做。

提前致谢。

2 个答案:

答案 0 :(得分:1)

这个怎么样?

var dates = Enumerable.Range(1, 5).Select(i=>new DateTime(2015,i%3+1,1));
var grouped = dates.GroupBy(d => d.Month).Select(g => string.Format("{0}={1}", g.Key, g.Count()));
// Now grouped will have your desired data (list of occurrences)

我在这里使用了虚拟日期。您需要Select数据库中的日期列。

答案 1 :(得分:0)

如果要使用lambda而不是long linq,可以执行以下操作。虽然您需要将数字月转换为texual。

var somedates = new List<DateTime>() { 
            DateTime.Now, 
            DateTime.Now.AddDays(10), 
            DateTime.Now.AddMonths(1), 
            DateTime.Now.AddMonths(1).AddDays(5)};

var months = somedates.GroupBy(x => x.Month).Select(g => new {Name = g.Key, Count = g.Count()});