This post will discuss how to sort a string array in C#.

1. Using Array.Sort() method

The standard solution to in-place sort elements of a single-dimensional string array is using the Array.Sort() method. Its default behavior is to sort the string array in alphabetical order, as shown below.

Download  Run Code

Output:

Array, C#, Sort

 
The Array.Sort() method is overloaded to accept custom comparers. For example, the following code uses the StringComparer.CurrentCultureIgnoreCase property to perform the case-insensitive string comparison using the word comparison rules of the current culture.

Download  Run Code

Output:

Array, c#, Sort

 
Here’s another example that takes a custom comparer to sort the string array by its length.

Download  Run Code

Output:

C#, Sort, Array

2. Using Enumerable.OrderBy Method

To get a sorted copy of the original array, consider using the Enumerable.OrderBy method by LINQ. The following code example demonstrates its usage to sort a string array alphabetically:

Download  Run Code

Output:

Array, C#, Sort

 
Like Array.Sort() method, the Enumerable.OrderBy() method is overloaded to accept custom comparers. For example, the following code uses a custom comparer to sort the string array by its length.

Download  Run Code

Output:

C#, Sort, Array

That’s all about sorting a string array in C#.