Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. C#
  4. How to sort a List in C#

How to sort a List in C#

Date- Jun 01,2023 Updated Jan 2026 3869
csharp list sorting

Understanding the List Class

The List class in C# is part of the System.Collections.Generic namespace and is a versatile collection that can dynamically resize. Unlike arrays, lists can grow or shrink as needed, making them ideal for scenarios where the number of elements is not known in advance. The List class provides multiple methods for manipulating data, including adding, removing, and sorting elements.

Using lists allows for efficient data management in various applications, whether you're building a simple console application or a complex web service. The ability to sort data improves readability and helps users find information quickly. This article will dive into various ways to sort lists in C#, covering both basic and advanced techniques.

Sorting a List in Ascending Order

To sort a list in C#, the Sort method is the most straightforward approach. By default, this method sorts elements in ascending order, which is useful for numerical and alphabetical sorting. For example, consider a list of integers:

List<int> numbers = new List<int> { 4, 2, 7, 1, 9 };
numbers.Sort();
Console.WriteLine(string.Join(", ", numbers)); // Output: 1, 2, 4, 7, 9

After executing the Sort method, the numbers list will be sorted in ascending order: { 1, 2, 4, 7, 9 }.

Sorting a List of Objects

When working with lists of objects, sorting can be done based on specific properties. This is achieved by passing a custom comparison function to the Sort method. For instance, if you have a list of Person objects and want to sort them by their Name property, you can do so as follows:

class Person {
public string Name { get; set; }
// other properties
}
List<Person> people = new List<Person> {
new Person { Name = "Alice" },
new Person { Name = "Charlie" },
new Person { Name = "Bob" }
};
people.Sort((p1, p2) => p1.Name.CompareTo(p2.Name));
Console.WriteLine(string.Join(", ", people.Select(p => p.Name))); // Output: Alice, Bob, Charlie

After executing the custom sort, the people list will be organized alphabetically by name: { "Alice", "Bob", "Charlie" }.

Sorting in Descending Order

If you need to sort a list in descending order, you can still use the Sort method with a custom comparison. Alternatively, you can sort in ascending order and then reverse the list. Here's how to sort a list of integers in descending order:

List<int> numbers = new List<int> { 4, 2, 7, 1, 9 };
numbers.Sort((x, y) => y.CompareTo(x));
Console.WriteLine(string.Join(", ", numbers)); // Output: 9, 7, 4, 2, 1

In this example, the Sort method sorts the numbers in descending order directly. As a result, the numbers list is now: { 9, 7, 4, 2, 1 }.

Sorting with LINQ

Another powerful way to sort lists in C# is by using LINQ (Language Integrated Query). LINQ provides a more readable and expressive syntax for querying and manipulating data. To sort a list using LINQ, you can use the OrderBy and OrderByDescending methods. Here’s an example:

using System.Linq;

List<int> numbers = new List<int> { 4, 2, 7, 1, 9 };
var sortedNumbers = numbers.OrderBy(n => n).ToList();
Console.WriteLine(string.Join(", ", sortedNumbers)); // Output: 1, 2, 4, 7, 9

In this case, OrderBy sorts the numbers in ascending order, and the result is converted back to a list using ToList().

Edge Cases & Gotchas

When sorting lists, there are a few edge cases and potential pitfalls to be aware of. One common issue arises when the list contains null values. If you attempt to sort a list with null elements, a NullReferenceException may be thrown. To handle this, ensure that your comparison function accounts for null values appropriately.

Another important consideration is the stability of the sort. The Sort method in C# is not guaranteed to be stable, meaning that equal elements may not retain their original order after sorting. If stability is a requirement, consider using LINQ's OrderBy method, which is stable.

Performance & Best Practices

Sorting algorithms can vary significantly in performance based on the size of the data set and the algorithm used. The default sorting algorithm used by the Sort method is QuickSort, which has an average time complexity of O(n log n). However, for small lists, the performance may not be optimal. In such cases, consider using Insertion Sort, which is efficient for small data sets.

When sorting large lists, it’s also essential to minimize the number of comparisons and swaps. To optimize sorting performance, avoid unnecessary sorting operations and consider whether the list can be partially sorted or if caching sorted results is feasible.

Here are some best practices when sorting lists in C#:

  • Always validate your data before sorting.
  • Be mindful of null values and handle them appropriately.
  • Use LINQ for more readable and maintainable code when appropriate.
  • Test performance with different data sizes to choose the best sorting method.

Conclusion

Sorting a list in C# is a fundamental skill that enhances data organization and accessibility. By understanding the various methods available, including the Sort method, custom comparisons, and LINQ, developers can efficiently manage and present data. Remember to consider edge cases, performance implications, and best practices when implementing sorting in your applications.

Key Takeaways:

  • The Sort method is the simplest way to sort lists in C#.
  • Custom comparisons allow sorting of complex objects by specific properties.
  • LINQ provides a readable alternative for sorting with stable results.
  • Be aware of null values and stability when sorting.
  • Optimize sorting performance based on data size and algorithm choice.

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Mastering Async and Await in C#: A Comprehensive Guide
Mar 16, 2026
How to Use Stored Procedures with Parameters in Dapper
Jan 23, 2024
Mastering LINQ in C#: A Complete Guide with Examples
Dec 09, 2023
DataReader in ADO.NET
May 31, 2023
Previous in C#
DataReader in ADO.NET
Next in C#
Replacing Accent Characters with Alphabet Characters in CSharp
Buy me a pizza

Comments

On this page

🎯

Interview Prep

Ace your C# interview with curated Q&As for all levels.

View C# Interview Q&As

More in C#

  • Zoom C# Wrapper Integration 12905 views
  • Convert HTML String To Image In C# 11504 views
  • The report definition is not valid or is not supported by th… 10856 views
  • Replacing Accent Characters with Alphabet Characters in CSha… 9843 views
  • Get IP address using c# 8690 views
View all C# posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor