Linq groupby Months and add missing months to grouped data

advertisements

I have created a linq statement which seems to be working ok. I may or maynot have written it correctly however its returning my expected results.

     var grouped = RewardTransctions.GroupBy(t => new
        {
            t.PurchaseDate.Value.Month
        }).Select(g => new TransactionDetail()
        {
            Month =
                g.Where(w=>w.EntryType==1).Select(
                    (n =>
                     n.PurchaseDate.Value.Month))
                .First(),
            TransactionAmount = g.Count()
        });

Now the results are returning 5 values grouped by months. Is it possible to add the 7 other missing months with a TransactionAmount = 0 to them?

The reason for my madness is I am trying to bind these values to a chart and having my x axis based on months. Currently its only showing the 5 months of records. If my data doesnt return any value for a month I some how want to add in the 0 value.

Any suggestions?


It's very simple if you use .ToLookup(...).

var lookup =
    (from w in RewardTransctions
     where w.EntryType == 1
     select w).ToLookup(w => w.PurchaseDate.Value.Month);

var grouped =
    from m in Enumerable.Range(1, 12)
    select new TransactionDetail()
    {
        Month = m,
        TransactionAmount = lookup[m].Count(),
    };

How's that for a couple of simple LINQ queries?