You are using the List constructed type in your program, and need to sort its contents in ascending or descending order, or by a property on the objects. The Sort method is ideal for some requirements, but you can use LINQ for a simple way to sort elements by properties.

Here we see how you can use the instance Sort method on your List to alphabetize its strings from A - Z. You could also specify a comparison function, or use the LINQ orderby keyword instead. This program will populate the List with three strings, and then sort them alphabetically. You can use the same method for integral types.
Program that uses Sort [C#]
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
Tip. You can combine the Sort method with the Reverse method to get a reverse sorted collection. Please see the linked example for details. Sort works with all value types and classes that implement the CompareTo method.
Reverse ListHere we see how you can 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, making this technique very useful in some programs.
Program that Sorts with LINQ [C#]
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
Notes. The important part to note in the code is that "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. You can specify "ascending" or "descending", such as with "orderby element.Length ascending".
OrderBy Clause Ascending Keyword Descending KeywordWe saw how you can sort List constructed types both with the Sort method and LINQ query syntax, which provides a simple way to order some collections. Additionally, we noted how the Reverse method can be used to specify that the List be ordered in the opposite order.
List Examples Sort Examples