Add Sub Totals to a LinQ Query.


description of the image
  
 public static void Test()
 {
   string sep = "------------------------------------------------------";
   var filteredExpenses = lstExpenses
  .Where(x => x.TransactionType == 1 && x.Payee.PayeeName != "Vanguard");
  var result = filteredExpenses
 .GroupBy(grp => new { grp.PurchaseMonth, grp.Category.CategoryName, grp.Category.CategoryID, grp.MonthName })
      .Select(o => new
         {
             o.Key.PurchaseMonth,
             o.Key.CategoryID,
             o.Key.MonthName,
             o.Key.CategoryName,
             Total_Amount = o.Sum(x => Math.Abs(x.Amount))
         }).OrderBy(x => x.PurchaseMonth).ThenByDescending(x => x.Total_Amount)

         // Subtotal Section
         .GroupBy(x => new { x.PurchaseMonth, x.MonthName }).Select(g => new
         {
             MonthNum = g.Key,
             g.Key.MonthName,
             SubTotal = g.Sum(x => x.Total_Amount),
             Categories = g.Select(x => new
             {
                 x.MonthName,
                 x.CategoryName,
                 x.CategoryID,
                 TotalAmount = x.Total_Amount
             }).ToList()
         });
     foreach (var month in result)
     {
         Console.WriteLine(sep);
         Console.WriteLine($"Month: {month.MonthName}, Subtotal: {month.SubTotal:C}");
         Console.WriteLine(sep);
         foreach (var category in month.Categories)
         {
             Console.WriteLine($"ID: {category.CategoryID}, " +
                 $"Category: {category.CategoryName}, " +
                 $"Total Amount: {category.TotalAmount:C}");
         }
         Console.WriteLine();
     }
  }