C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
The Sort method modifies the same List instance. It does not copy the List elements. Other methods too can sort a List—these include query expressions in the LINQ syntax.
Also: We show how to sort List elements on a property of the element type with the orderby keyword.
Example. First, here we use the instance Sort method on a List to alphabetize its strings from A - Z. You could also specify a comparison function, or use the LINQ orderby keyword instead.
Then: This program will populate the List with three strings, and sort them alphabetically. You can use the same method for integral types.
C# program that uses Sort using System; using System.Collections.Generic; class Program { static void Main() { List<string> list = new List<string>(); list.Add("tuna"); list.Add("velvetfish"); list.Add("angler"); // Sort fish alphabetically, in ascending order (A - Z) list.Sort(); foreach (string value in list) { Console.WriteLine(value); } } } Output angler tuna velvetfish
Also, you can combine the Sort method with the Reverse extension method to get a reverse sorted collection. Sort works with all value types and classes that implement the CompareTo method.
Example 2. Here we use the LINQ orderby keyword to sort a List by any property. This makes it simple to sort based on string length, or a property value in any object type. LINQ works on IEnumerable collections, which include List.
IEnumerable Examples: LINQ, Lists and Arrays
C# program that Sorts with LINQ using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<string> list = new List<string>(); list.Add("mississippi"); // Longest list.Add("indus"); list.Add("danube"); list.Add("nile"); // Shortest var lengths = from element in list orderby element.Length select element; foreach (string value in lengths) { Console.WriteLine(value); } } } Output nile indus danube mississippi
We see the "var" query expression. The orderby keyword is called a contextual keyword, and in this place it means to order the List elements by their lengths. The query is similar to ones written in SQL.
Tip: You can specify "ascending" or "descending", such as with "orderby element.Length ascending".
OrderBy ClauseAscending KeywordDescending Keyword
Summary. We sorted List constructed types both with the Sort method and LINQ query syntax, which provides a simple way to order some collections. The Reverse method can be used to specify that the List be ordered in the opposite order.