CodexBloom - Programming Q&A Platform

Sorting a List of Custom Objects by Multiple Attributes in C# - Unexpected Order Issues

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-21
c# sorting linq C#

I've been researching this but Quick question that's been bugging me - I'm stuck on something that should probably be simple. I'm stuck on something that should probably be simple. I'm trying to sort a list of custom objects in C# based on multiple attributes, but I'm running into an unexpected order scenario. I'm using .NET 6 and have a class called `Person` with properties `FirstName`, `LastName`, and `Age`. My goal is to sort the list first by `LastName`, then by `FirstName`, and finally by `Age` if there are ties. Here’s the code I'm using: ```csharp using System; using System.Collections.Generic; using System.Linq; public class Person { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } } var people = new List<Person> { new Person { FirstName = "John", LastName = "Doe", Age = 30 }, new Person { FirstName = "Jane", LastName = "Doe", Age = 25 }, new Person { FirstName = "Alice", LastName = "Smith", Age = 30 }, new Person { FirstName = "Bob", LastName = "Smith", Age = 22 } }; var sortedPeople = people.OrderBy(p => p.LastName) .ThenBy(p => p.FirstName) .ThenBy(p => p.Age) .ToList(); ``` When I print the sorted list, the output is: ``` John Doe, 30 Jane Doe, 25 Alice Smith, 30 Bob Smith, 22 ``` However, I expected the `Jane Doe` entry to come before `John Doe`, because `Jane` is alphabetically before `John`. It seems the sorting is not respecting the order when there's a tie in the `LastName`. I've confirmed that I'm using the correct sorting methods and even tried debugging by printing the properties right before sorting, but the output still seems off. I feel like there's something subtle I'm missing here. Could anyone guide to understand why the sorting isn't working as expected? For context: I'm using C# on macOS. Am I missing something obvious? Thanks for any help you can provide! I'm using C# 3.11 in this project. Hoping someone can shed some light on this. Thanks, I really appreciate it! This issue appeared after updating to C# latest. Is this even possible?