CodexBloom - Programming Q&A Platform

advanced patterns when using LINQ to filter and project complex objects in C#

šŸ‘€ Views: 19 šŸ’¬ Answers: 1 šŸ“… Created: 2025-07-02
c# linq dotnet linq-to-objects C#

I'm migrating some code and I've searched everywhere and can't find a clear answer... I'm working with an odd scenario while trying to filter and project a list of complex objects using LINQ in my C# application. My goal is to filter a list of `Order` objects based on their `Status`, then create a new list of anonymous objects containing just the `OrderId` and `TotalAmount`. However, when executing the LINQ query, I get an empty list instead of the expected results. Here's a simplified version of my code: ```csharp public class Order { public int OrderId { get; set; } public decimal TotalAmount { get; set; } public string Status { get; set; } } List<Order> orders = new List<Order> { new Order { OrderId = 1, TotalAmount = 100.00m, Status = "Completed" }, new Order { OrderId = 2, TotalAmount = 200.00m, Status = "Pending" }, new Order { OrderId = 3, TotalAmount = 300.00m, Status = "Completed" }, }; var completedOrders = orders .Where(o => o.Status == "Completed") .Select(o => new { o.OrderId, o.TotalAmount }) .ToList(); ``` After executing this code, `completedOrders` is an empty list. I checked the values of `Status` in the original list, and they seem to be correct. I even tried debugging to see if the `Where` clause is being evaluated correctly, and it looks like it is. I thought maybe it was a case-sensitivity scenario, so I also tried: ```csharp .Where(o => o.Status.Equals("Completed", StringComparison.OrdinalIgnoreCase)) ``` Still, I get an empty result. My LINQ query runs perfectly in LINQPad, so I'm wondering if there's something about the execution context in my application that's affecting it. I’m using .NET 6 and running this code in a console app. Has anyone encountered a similar scenario or know what could be causing this behavior? Any insights would be greatly appreciated! This is my first time working with C# latest. The project is a microservice built with C#. Any feedback is welcome!