CodexBloom - Programming Q&A Platform

C# 11 - Null Reference Exception when using LINQ with Record Types in Group By Clause

👀 Views: 3 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
c# linq record-types C#

I need help solving I'm trying to implement I'm collaborating on a project where I'm encountering a `NullReferenceException` when trying to group a list of records using LINQ in C# 11... I have a simple record type defined as follows: ```csharp public record Product(string Name, decimal? Price); ``` I created a list of products and am attempting to group them by the `Price` property, which can be null. Here's the relevant code snippet: ```csharp var products = new List<Product> { new Product("Apple", 1.20m), new Product("Banana", null), new Product("Cherry", 2.50m), new Product("Date", null) }; var groupedProducts = from product in products group product by product.Price into g select new { Price = g.Key, Products = g.ToList() }; ``` When I run this code, I receive the following exception: ``` System.NullReferenceException: Object reference not set to an instance of an object. ``` After checking, I found that the exception occurs at the `group product by product.Price` line. I suspect it might be due to how LINQ handles null values in the `group by` clause. I tried using the `DefaultIfEmpty()` method to handle possible null values but that didn't seem to resolve the issue. I also tried adding a null check before the grouping: ```csharp var groupedProducts = from product in products where product.Price.HasValue group product by product.Price into g select new { Price = g.Key, Products = g.ToList() }; ``` However, this filters out products with null prices entirely, which is not what I want. I want to group products with `null` prices separately. How can I modify my LINQ query to achieve this without running into `NullReferenceException`? Any ideas what could be causing this? The project is a service built with C#.