CodexBloom - Programming Q&A Platform

Sorting a Large List of Complex Objects with Custom Attributes in C# - Performance Issues and Unexpected Results

👀 Views: 100 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-04
c# linq sorting performance C#

I'm relatively new to this, so bear with me. I'm maintaining legacy code that I'm trying to configure I'm stuck on something that should probably be simple..... I'm sure I'm missing something obvious here, but I'm working on a C# application targeting .NET 5.0, where I need to sort a large list of custom objects... Each object has several properties, including a string for a name, a DateTime for a registration date, and a decimal for a score. My goal is to sort this list primarily by the score in descending order, and then by the registration date in ascending order for items with the same score. Here's a simplified version of my class: ```csharp public class User { public string Name { get; set; } public DateTime RegistrationDate { get; set; } public decimal Score { get; set; } } ``` I have a list of `User` objects that I am trying to sort: ```csharp List<User> users = new List<User>() { new User() { Name = "Alice", RegistrationDate = new DateTime(2022, 5, 1), Score = 95.5m }, new User() { Name = "Bob", RegistrationDate = new DateTime(2022, 3, 15), Score = 95.5m }, new User() { Name = "Charlie", RegistrationDate = new DateTime(2023, 1, 10), Score = 88.0m } }; ``` I tried to sort the list using LINQ like this: ```csharp var sortedUsers = users.OrderByDescending(u => u.Score) .ThenBy(u => u.RegistrationDate) .ToList(); ``` However, I noticed that when there are users with the same score, the order of registration dates is not as expected. For instance, "Alice" and "Bob" both have a score of 95.5, but it seems that the order of their registration dates is not being respected. Sometimes, it looks random. I also measured the performance of this sorting operation when the list size exceeds 100,000 entries. The operation becomes noticeably slower, and I'm concerned about its efficiency. Is there a more performant way to handle this sorting, or am I missing something in the LINQ implementation? Any suggestions on how to optimize this would be very helpful! I'd really appreciate any guidance on this. What would be the recommended way to handle this? My team is using C# for this microservice. This is for a microservice running on Ubuntu 22.04. Any feedback is welcome! This is my first time working with C# LTS. What are your experiences with this?