CodexBloom - Programming Q&A Platform

NullReferenceException When Accessing Nested Properties in C# with LINQ

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-28
c# linq nullreferenceexception dotnet6 csharp

Does anyone know how to I'm relatively new to this, so bear with me. I'm encountering a `NullReferenceException` when trying to access nested properties using LINQ in a collection of objects. I have a list of `Order` objects, and each `Order` contains a `Customer` object, which in turn has a `ShippingAddress`. The issue arises when some `Customer` objects are null, which I want to handle gracefully. Here’s a simplified version of my code: ```csharp public class Customer { public string Name { get; set; } public string ShippingAddress { get; set; } } public class Order { public int OrderId { get; set; } public Customer Customer { get; set; } } var orders = new List<Order> { new Order { OrderId = 1, Customer = new Customer { Name = "John", ShippingAddress = "123 Elm St" }}, new Order { OrderId = 2, Customer = null }, new Order { OrderId = 3, Customer = new Customer { Name = "Jane", ShippingAddress = "456 Oak St" }} }; var shippingAddresses = orders.Select(o => o.Customer.ShippingAddress).ToList(); ``` When I run this code, I get a `NullReferenceException` on the line where I try to access `o.Customer.ShippingAddress`. I’ve tried adding null checks in the LINQ query, but I’m not sure how to implement it correctly. I attempted the following code, but it doesn't compile: ```csharp var shippingAddresses = orders.Select(o => o.Customer != null ? o.Customer.ShippingAddress : null).ToList(); ``` This seems to work, but I suspect there is a more idiomatic way to handle this scenario. Additionally, I’d like to ensure that I only include addresses that are not null in the final list. Can someone suggest a better approach for this, perhaps using `?.` operator or any other LINQ method that would be more efficient? I'm using .NET 6 for this implementation, and I want to adhere to best practices for performance and readability. I'd really appreciate any guidance on this. The stack includes Csharp and several other technologies.