---
title: "How to sort a List in C#?"  
description: "How to sort a List in C#?"  
author: "Steilla Mitchel"  
published: 2023-08-17  
updated: 2023-08-18  
canonical: https://www.mindstick.com/forum/159563/how-to-sort-a-list-in-c-sharp  
category: "c#"  
tags: ["c#", "list"]  
reading_time: 2 minutes  

---

# How to sort a List in C#?

How to sort a List in C#?

## Replies

### Reply by Aryan Kumar

There are two ways to sort a list in C#:

- Using the `Sort()` method.
- Using the `OrderBy()` method from LINQ.

**Using the** `Sort()` **method**

The `Sort()` method takes a delegate as its parameter. The delegate is a function that takes two elements of the same type and returns an integer value indicating their relative order. The following code sorts a list of integers in ascending order:

C#

```plaintext
List<int> numbers = new List<int>();
numbers.Add(10);
numbers.Add(5);
numbers.Add(20);

numbers.Sort(delegate(int x, int y) {
    return x.CompareTo(y);
});
```

In this code, the delegate is an anonymous method that compares two integers. The `CompareTo()` method returns an integer value indicating the relative order of the two integers. A value of -1 means that the first integer is less than the second integer, a value of 0 means that the two integers are equal, and a value of 1 means that the first integer is greater than the second integer.

**Using the** `OrderBy()` **method from LINQ**

The `OrderBy()` method from LINQ is a more concise way to sort a list. The `OrderBy()` method takes a lambda expression as its parameter. The lambda expression specifies the property that the list should be sorted by. The following code sorts the same list of integers as the previous example using the `OrderBy()` method:

C#

```plaintext
var sortedNumbers = numbers.OrderBy(x => x);
```

In this code, the lambda expression specifies that the list should be sorted by the `x` property of the `int` objects.

Which method you use to sort a list depends on your preference. The `Sort()` method is more flexible, as you can use it to sort a list by any property. However, the `OrderBy()` method is more concise and easier to read.


---

Original Source: https://www.mindstick.com/forum/159563/how-to-sort-a-list-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
