linq

2012-03-20 33 views
1

查询表中的每月记录我有一个名为testable的数据表,它有两列id(主键,int)和时间(日期时间)。我想计算表中每个特定月份的记录数。例如,有5个表中的行,linq

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/12月份,它不能查询其他月份的记录。 任何人都可以提供帮助吗?

+0

但是,您向我们展示的数据仅包含3/4/8/12的行,所以它工作正常。 – MarcinJuraszek 2012-03-20 05:33:00

回答

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); 
}