---
title: "How to sort an array in C#?"  
description: "How to sort an array in C#?"  
author: "Steilla Mitchel"  
published: 2024-06-11  
updated: 2024-06-11  
canonical: https://www.mindstick.com/forum/160712/how-to-sort-an-array-in-c-sharp  
category: "c#"  
tags: ["c#", ".net"]  
reading_time: 2 minutes  

---

# How to sort an array in C#?

How to [sort an array in C#](https://answers.mindstick.com/qa/82449/how-to-sort-an-array-in-c-sharp)?

## Replies

### Reply by Ravi Vishwakarma

You can [sort an array](https://www.mindstick.com/forum/157933/write-a-program-to-sort-an-array-of-integers-using-the-bubble-sort-algorithm) using various methods provided by the language. \
Here are a few common ways to do it:

**Using Array.Sort Method**\
The **Array.Sort** method is a simple and efficient way to sort arrays of primitive types or objects that implement the **IComparable interface:**

```cs
int[] numbers = { 3, 1, 4, 1, 5, 9, 2, 6, 5 };
Array.Sort(numbers);
```

**Using Array.Sort with Comparison Delegate**\
You can also use the **Array.Sort** method with a comparison delegate to define custom sorting logic:

```cs
string[] names = { "John", "Alice", "Bob", "Eve" };
Array.Sort(names, (x, y) => string.Compare(x, y));
```

**Using LINQ OrderBy Method**\
If you're working with arrays of objects, you can use **LINQ's OrderBy method** to sort them based on a specified key:

```cs
string[] names = { "John", "Alice", "Bob", "Eve" };
names = names.OrderBy(name => name).ToArray();
```

**Using LINQ OrderByDescending Method**\
Similarly, you can use [**LINQ's OrderByDescending method**](https://www.mindstick.com/articles/12007/language-integrated-query-linq-queries) to sort in descending order:

```cs
string[] names = { "John", "Alice", "Bob", "Eve" };
names = names.OrderByDescending(name => name).ToArray();
```

**Using Custom Comparison Logic**\
If you need to sort based on custom logic, you can implement the **IComparer<T>** interface and use the **Array.Sort** method overload that takes an **IComparer<T>** parameter:

```cs
class CustomComparer : IComparer<int>
{
   public int Compare(int x, int y)
   {
       // Custom comparison logic
       return x.CompareTo(y);
   }
}
int[] numbers = { 3, 1, 4, 1, 5, 9, 2, 6, 5 };
Array.Sort(numbers, new CustomComparer());
```

**Result**\
Regardless of the method you choose, the array will be sorted in ascending order by default, or in the specified order based on the comparison logic provided. Adjust the sorting logic according to your requirements.


---

Original Source: https://www.mindstick.com/forum/160712/how-to-sort-an-array-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
