---
title: "How do I sort a generic list?"  
description: "How do I sort a generic list?"  
author: "Revati S Misra"  
published: 2023-08-18  
updated: 2023-08-19  
canonical: https://www.mindstick.com/forum/159572/how-do-i-sort-a-generic-list  
category: "c#"  
tags: ["c#", "sorting"]  
reading_time: 2 minutes  

---

# How do I sort a generic list?

How do I sort a generic list?

## Replies

### Reply by Aryan Kumar

To sort a generic list in C#, you can use the `Sort()` method. The `Sort()` method takes a delegate as its parameter. The delegate is a function that takes two objects of the same type and returns an integer.

The following code sorts a generic list of strings in ascending order:

C#

```plaintext
List<string> names = new List<string>();
names.Add("John");
names.Add("Jane");
names.Add("Peter");

// Sort the list in ascending order.
names.Sort((string s1, string s2) => s1.CompareTo(s2));
```

In this example, the delegate takes two strings as its parameters and returns an integer. The integer returned by the delegate indicates the order of the two strings. In this case, the delegate compares the two strings lexicographically and returns a negative integer if the first string is less than the second string, a positive integer if the first string is greater than the second string, and 0 if the two strings are equal.

The `Sort()` method will sort the list in ascending order by default. If you want to sort the list in descending order, you can pass `true` as the second parameter to the `Sort()` method.

Here is the code to sort the list in descending order:

C#

```plaintext
names.Sort((string s1, string s2) => s1.CompareTo(s2), true);
```

The `Sort()` method can also be used to sort lists of objects that implement the `IComparable` interface. The `IComparable` interface defines a single method, `CompareTo()`, which takes another object of the same type as its parameter and returns an integer. The integer returned by the `CompareTo()` method indicates the order of the two objects.

The following code sorts a list of objects that implement the `IComparable` interface:

C#

```plaintext
class Person : IComparable<Person> {
    public int Age { get; set; }

    public int CompareTo(Person other) {
        return this.Age - other.Age;
    }
}

List<Person> people = new List<Person>();
people.Add(new Person { Age = 10 });
people.Add(new Person { Age = 20 });
people.Add(new Person { Age = 30 });

// Sort the list by the Age property.
people.Sort();
```

In this example, the `Person` class implements the `IComparable` interface. The `CompareTo()` method compares the ages of the two `Person` objects and returns the difference.


---

Original Source: https://www.mindstick.com/forum/159572/how-do-i-sort-a-generic-list

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
