CodexBloom - Programming Q&A Platform

Strange behavior with LINQ’s GroupBy and SelectMany in C# causing unexpected results

👀 Views: 75 💬 Answers: 1 📅 Created: 2025-08-28
c# linq groupby selectmany C#

I've been struggling with this for a few days now and could really use some help. I'm encountering an odd issue when using LINQ's `GroupBy` followed by `SelectMany` in my C# application. My goal is to group a list of `Orders` by `CustomerId` and then flatten the results to get a list of all `OrderItems` for each customer. However, I'm seeing repeated entries in the final result, which I didn't expect. Here's my code snippet: ```csharp public class Order { public int CustomerId { get; set; } public List<OrderItem> Items { get; set; } } public class OrderItem { public int ProductId { get; set; } public int Quantity { get; set; } } var orders = new List<Order> { new Order { CustomerId = 1, Items = new List<OrderItem> { new OrderItem { ProductId = 101, Quantity = 2 } } }, new Order { CustomerId = 2, Items = new List<OrderItem> { new OrderItem { ProductId = 102, Quantity = 1 } } }, new Order { CustomerId = 1, Items = new List<OrderItem> { new OrderItem { ProductId = 103, Quantity = 5 } } } }; var orderItems = orders .GroupBy(o => o.CustomerId) .SelectMany(g => g.SelectMany(o => o.Items)); ``` When I run this code, I expect to end up with a flat list of all `OrderItems` regardless of which customer they belong to. However, the resulting collection contains duplicate `OrderItems` for `ProductId 101` and `ProductId 103` which should not happen when flattening the list. Specifically, the output looks like this: - ProductId: 101, Quantity: 2 - ProductId: 103, Quantity: 5 - ProductId: 101, Quantity: 2 - ProductId: 103, Quantity: 5 I've checked for duplicates in the `Order` objects, but I don't see any. What could be causing this issue? Am I misunderstanding how `GroupBy` and `SelectMany` are operating together? I’m using .NET 5.0 and have tried running this in LINQPad as well, but the results are the same. Any insights would be greatly appreciated! Any help would be greatly appreciated! This is my first time working with C# 3.9.