LINQ - Group By Month, Sum some value and count

The following example group an list by year, month. It counts how much records the groups has and sums some values from the group (in this case is money).

var orders = from ord in Lista group enc by new {

                                                  ord.DateOfPayment.Value.Year,
                                                  ord.DateOfPayment.Value.Month
                                              }
                             into g
                             select new
                                        {
                                            Month \= g.Select(n \=> n.DateOfPayment.Value.Month).First(),
                                            TotalAmount \= g.Sum(n \=> (Decimal) n.TotalAmount),
                                            CountOrders \= g.Count()
                                        };
This article is part of the GWB Archives. Original Author: Guilherme Cardoso

New on Geeks with Blogs