Time-Based Grouping: Analyzing Time Series Data

Group and analyze data based on time periods:

var transactions = new List<Transaction>
{
    new Transaction { 
        Date = DateTime.Parse("2024-01-01"), 
        Amount = 100 
    },
    new Transaction { 
        Date = DateTime.Parse("2024-01-15"), 
        Amount = 200 
    },
    new Transaction { 
        Date = DateTime.Parse("2024-02-01"), 
        Amount = 150 
    }
};

var monthlyAnalysis = transactions
    .GroupBy(t => new { 
        Year = t.Date.Year, 
        Month = t.Date.Month 
    })
    .Select(g => new {
        Period = new DateTime(g.Key.Year, g.Key.Month, 1),
        TransactionCount = g.Count(),
        TotalAmount = g.Sum(t => t.Amount),
        AverageAmount = g.Average(t => t.Amount),
        DailyTransactions = g
            .GroupBy(t => t.Date.Date)
            .Select(d => new {
                Date = d.Key,
                Amount = d.Sum(t => t.Amount)
            })
    });

// Results:
// January 2024: 2 transactions, Total: 300, Average: 150
// February 2024: 1 transaction, Total: 150, Average: 150