Sort a List of strings in C#
This post will discuss how to sort a list of strings in C#.
1. Using Enumerable.OrderBy Method
A simple solution to get a sorted copy of a List is using the Enumerable.OrderBy method. It sorts all items contained in a sequence in ascending order according to a key or a specified comparer. The following example demonstrates its usage to sort elements of a list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<string> strings = new List<string>() { "A", "B", "C", "D", "E" }; var sortedList = strings.OrderBy(x => x).ToList(); Console.WriteLine(String.Join(", ", sortedList)); // A, B, C, D, E } } |
2. Using List<T>.Sort Method
A concise and efficient solution to in-place sort elements of a list is using the List<T>.Sort method. We can use it to sort the complete list or a portion of it with the specified comparer. The following example demonstrates its usage to sort the values of a list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<string> strings = new List<string>() { "A", "B", "C", "D", "E" }; strings.Sort(); Console.WriteLine(String.Join(", ", strings)); // A, B, C, D, E } } |
That’s all about sorting a list of strings 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 :)