CodexBloom - Programming Q&A Platform

Sorting a List of Custom Objects by Calculated Property in C# - Unexpected Order with EqualityComparer

๐Ÿ‘€ Views: 0 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-14
c# sorting linq C#

I'm relatively new to this, so bear with me... I'm trying to sort a list of custom objects in C# based on a calculated property, but Iโ€™m running into unexpected ordering issues. My objects are of a class `Product` which has properties `Name`, `BasePrice`, and a calculated property `FinalPrice` that includes discounts. Hereโ€™s the `Product` class and the sorting code: ```csharp public class Product { public string Name { get; set; } public decimal BasePrice { get; set; } public decimal Discount { get; set; } public decimal FinalPrice => BasePrice - Discount; } var products = new List<Product> { new Product { Name = "Product A", BasePrice = 100, Discount = 10 }, new Product { Name = "Product B", BasePrice = 200, Discount = 50 }, new Product { Name = "Product C", BasePrice = 150, Discount = 0 } }; var sortedProducts = products.OrderBy(p => p.FinalPrice).ToList(); ``` However, when I run this code, the `sortedProducts` list does not seem to be sorted correctly by `FinalPrice`. For instance, I expect `Product B` to come first because its `FinalPrice` should be `150`, but it appears last in the sorted list. Iโ€™ve checked that `BasePrice` and `Discount` are being set correctly, and even added a debug line to print the `FinalPrice` during sorting: ```csharp foreach (var product in products) { Console.WriteLine($"{product.Name}: {product.FinalPrice}"); } ``` This outputs: - Product A: 90 - Product B: 150 - Product C: 150 I suspect it might be related to how `OrderBy` handles items with equal `FinalPrice` values. Is there a way to ensure that when two products have the same `FinalPrice`, they are sorted by `Name` as a secondary criterion? Iโ€™ve tried using `ThenBy` but still see inconsistencies. Any advice on how to resolve this scenario would be greatly appreciated! I'd really appreciate any guidance on this. For context: I'm using C# on Ubuntu. Am I missing something obvious?