C# 9 - Nullable Reference Types and LINQ Queries Causing NullReferenceException in Nested Collections
I've spent hours debugging this and I'm encountering a `NullReferenceException` when executing a LINQ query that involves a collection of objects with nullable reference types in C# 9. My classes are defined as follows: ```csharp public class User { public int Id { get; set; } public string? Name { get; set; } public List<Order>? Orders { get; set; } } public class Order { public int OrderId { get; set; } public string? ProductName { get; set; } } ``` I have a list of users, and I'm attempting to get a list of product names from their orders. Here is the LINQ query I used: ```csharp List<User> users = GetUsers(); // Assume this returns a list of users var productNames = users.SelectMany(user => user.Orders.Select(order => order.ProductName)).ToList(); ``` The issue arises when some users don't have any orders, leading to a `NullReferenceException` when trying to access `user.Orders`. I tried checking for null like this: ```csharp var productNames = users.SelectMany(user => user.Orders?.Select(order => order.ProductName) ?? Enumerable.Empty<string>()).ToList(); ``` However, this still results in the same exception. I've verified that `Nullable Reference Types` are enabled in my project settings, but it seems like the query isn't properly handling the null checks. Is there a more effective way to structure this LINQ query to avoid the exception and ensure that I only get product names for users who have orders? I'm using .NET 5.0, and I'd appreciate any insights into best practices for handling nullable collections in LINQ queries. I'd be grateful for any help. This is happening in both development and production on Ubuntu 22.04. What are your experiences with this?