CodexBloom - Programming Q&A Platform

LINQ GroupBy with Conditional Aggregation in C# - Unexpected Results

πŸ‘€ Views: 39 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
c# linq groupby csharp

I'm updating my dependencies and I'm following best practices but I'm experimenting with I tried several approaches but none seem to work... This might be a silly question, but I'm trying to perform a `GroupBy` operation on a collection of sales records, where I want to aggregate the total sales amounts based on a specific condition, but the results aren't matching my expectations. I have a list of `Sale` objects, each containing properties for `ProductId`, `Amount`, and `IsReturned`. I want to group the sales by `ProductId` and sum only the amounts where `IsReturned` is false. Here's my LINQ query: ```csharp public class Sale { public int ProductId { get; set; } public decimal Amount { get; set; } public bool IsReturned { get; set; } } var sales = new List<Sale> { new Sale { ProductId = 1, Amount = 100, IsReturned = false }, new Sale { ProductId = 1, Amount = 50, IsReturned = true }, new Sale { ProductId = 2, Amount = 200, IsReturned = false }, new Sale { ProductId = 2, Amount = 30, IsReturned = true } }; var result = sales .GroupBy(s => s.ProductId) .Select(g => new { ProductId = g.Key, TotalSales = g.Where(s => !s.IsReturned).Sum(s => s.Amount) }).ToList(); ``` When I run this code, the `result` variable contains the following: ``` ProductId: 1, TotalSales: 100 ProductId: 2, TotalSales: 200 ``` I expected the `TotalSales` for `ProductId: 1` to be 100 (as the `50` amount is from a returned sale and shouldn't be included) and for `ProductId: 2` to be 200 (since there is a `30` amount from a returned sale). However, it seems to be aggregating all sales for both products. I've also tried debugging by breaking it down into two steps, first filtering the sales and then grouping them, but I still get the same result. Here’s that attempt: ```csharp var filteredSales = sales.Where(s => !s.IsReturned); var result = filteredSales .GroupBy(s => s.ProductId) .Select(g => new { ProductId = g.Key, TotalSales = g.Sum(s => s.Amount) }).ToList(); ``` Still doesn't yield the expected results. Any ideas on why the `GroupBy` and `Where` combination isn't working as I anticipated? Am I missing something in the LINQ syntax or logic? I'm using .NET 6.0 and LINQ to Objects. Thanks for any insights! How would you solve this? What would be the recommended way to handle this? I'm developing on CentOS with Csharp. I appreciate any insights! I'm using Csharp 3.10 in this project. I'm working with Csharp in a Docker container on macOS.