0
0
CsharpHow-ToBeginner · 3 min read

How to Sort List in C#: Simple Guide with Examples

In C#, you can sort a list using the List<T>.Sort() method, which sorts the list in place in ascending order. For custom sorting, you can pass a comparison delegate or use LINQ's OrderBy() to create a sorted copy.
📐

Syntax

The basic syntax to sort a list in C# is using the Sort() method of the List<T> class. You can call it without parameters to sort in ascending order, or provide a Comparison<T> delegate to customize the order.

  • myList.Sort(); - Sorts the list in ascending order.
  • myList.Sort((a, b) => a.CompareTo(b)); - Sorts using a custom comparison.

Alternatively, use LINQ's OrderBy() to get a new sorted sequence without changing the original list.

csharp
myList.Sort();

// Or with custom comparison
myList.Sort((a, b) => a.CompareTo(b));

// Using LINQ to get a sorted copy
var sortedList = myList.OrderBy(x => x).ToList();
💻

Example

This example shows how to sort a list of integers in ascending order using Sort(). It also demonstrates sorting strings alphabetically.

csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 5, 3, 8, 1, 4 };
        numbers.Sort();
        Console.WriteLine("Sorted numbers: " + string.Join(", ", numbers));

        List<string> fruits = new List<string> { "banana", "apple", "cherry" };
        fruits.Sort();
        Console.WriteLine("Sorted fruits: " + string.Join(", ", fruits));
    }
}
Output
Sorted numbers: 1, 3, 4, 5, 8 Sorted fruits: apple, banana, cherry
⚠️

Common Pitfalls

One common mistake is expecting Sort() to return a new sorted list, but it sorts the list in place and returns void. Another pitfall is not providing a proper comparison when sorting complex objects, which can cause runtime errors or incorrect order.

Also, using OrderBy() without converting back to a list leaves you with an IEnumerable<T>, not a List<T>.

csharp
/* Wrong: expecting Sort() to return a sorted list */
List<int> nums = new List<int> {3, 1, 2};
// List<int> sortedNums = nums.Sort(); // This causes a compile error

/* Right: Sort in place */
nums.Sort();

/* Wrong: sorting complex objects without comparison */
class Person { public string Name; }
List<Person> people = new List<Person> { new Person { Name = "Bob" }, new Person { Name = "Alice" } };
// people.Sort(); // Throws exception

/* Right: provide comparison */
people.Sort((p1, p2) => p1.Name.CompareTo(p2.Name));
📊

Quick Reference

Here is a quick summary of sorting methods for lists in C#:

MethodDescriptionReturns
List<T>.Sort()Sorts the list in ascending order in placevoid
List<T>.Sort(Comparison<T>)Sorts the list using a custom comparisonvoid
Enumerable.OrderBy()Returns a new sorted sequence without changing original listIEnumerable<T>
Enumerable.OrderByDescending()Returns a new sequence sorted in descending orderIEnumerable<T>

Key Takeaways

Use List<T>.Sort() to sort a list in place in ascending order.
Provide a comparison delegate to Sort() for custom sorting logic.
Use LINQ's OrderBy() to get a sorted copy without modifying the original list.
Remember Sort() returns void and modifies the list directly.
For complex objects, always define how to compare them before sorting.