Sort a string array in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string[] arr = { "Sort", "Array", "C#" }; Array.Sort(arr); Console.WriteLine(String.Join(", ", arr)); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string[] arr = { "Sort", "Array", "c#" }; Array.Sort(arr, StringComparer.CurrentCultureIgnoreCase); Console.WriteLine(String.Join(", ", arr)); } } |
Output:
Array, c#, Sort
Here’s another example that takes a custom comparer to sort the string array by its length.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string[] arr = { "Sort", "Array", "C#" }; Array.Sort(arr, (x, y) => x.Length.CompareTo(y.Length)); Console.WriteLine(String.Join(", ", arr)); } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Linq; public class Example { public static void Main() { string[] arr = { "Sort", "Array", "C#" }; string[] sorted = arr.OrderBy(x => x).ToArray(); Console.WriteLine(String.Join(", ", sorted)); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Linq; public class Example { public static void Main() { string[] arr = { "Sort", "Array", "C#" }; string[] sortedByLength = arr.OrderBy(a => a.Length).ToArray(); Console.WriteLine(String.Join(", ", sortedByLength)); } } |
Output:
C#, Sort, Array
That’s all about sorting a string array in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)