通过linq查询表中的每个月记录

时间:2012-03-20 04:59:13

标签: linq

我有一个名为testable的数据表,它有两列id(主键,int)和time(datetime)。我想计算表中每个特定月份的记录数。例如,表格中有5行,

Id       datetime(d/m/y)
1   12/3/2011
2   15/3/2011
3   4/4/2011
4   1/8/2011
5   19/12/2011

如何编写Linq查询来查询这样的记录,

Id       datetime           count
1.  1/2011      0
2.  2/2011      0
3.  3/2011      2
4.  4/2011      1
5.  5/2011      0
6.  6/2011      0
7.  7/2011      0
8.  8/2011      1
9.  9/2011      0
10. 10/2011           0
11. 11/2011           0
12. 12/2011           1

我写了一个像这样的查询语句,

var query = from c in testtable.AsEnumerable()
                         group c by new
                         {
                             years = Convert.ToDateTime(c.Field<string>("Posted")).Year,
                             months = Convert.ToDateTime(c.Field<string>("Posted")).Month
                         }
                             into d
                             orderby d.Key.years,d.Key.months
                             select new
                             {
                                 Date = String.Format("{0}/{1}",d.Key.months,d.Key.years),                             
                                 Count = d.Count()
                             };

但它只查询当月的3/4/8月,它无法查询其他月份记录。 有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

您需要生成所有日期的序列,并使用该序列将现有查询加入。

var allMonths = Enumerable.Range(1, 12)
    .Select(i => String.Format("{0}/{1}", i, "2011"));
var query = new[]
{
    new{ Date= "3/2011" , Count = 2},
    new{ Date= "4/2011" , Count = 1},
    new{ Date= "8/2011" , Count = 1},
    new{ Date= "12/2011", Count = 1},
};

var query2 = from month in allMonths
             join date in query on month equals date.Date into g
             from date in g.DefaultIfEmpty()
             select new
             {
                 Date = month,
                 Count = (date == null) ? 0 : date.Count
             };

foreach (var q in query2)
{
    Console.WriteLine(q);
}
相关问题