James
James

Reputation: 2610

query each month record in the table by linq

I have a datatable named testable, it has two columns id(primary key, int) and time(datetime). I want to calculate the number of records of every specific month in the table. For example, there are 5 rows in the table,

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

How to write a Linq query to query out the record like this,

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

I have written a query statement like this,

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

But it only queries out the month 3/4/8/12, it can’t query out other month records. Anyone can help?

Upvotes: 1

Views: 475

Answers (1)

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

You need to generate a sequence of all dates and left join your existing query with that sequence.

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

Upvotes: 2

Related Questions