C# Sort List Method, Sorting and Reversing Lists

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 look at how you can use the parameterless Sort instance method on List, and also the Reverse method and LINQ query expressions with List in the C# programming language.

Arrow that indicates sorting objects

Sorting List

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 of the program ===

angler
tuna
velvetfish

Note on sorting. You can combine the Sort method with the Reverse method to get a reverse sorted collection. Please see the next example for details. Sort works with all value types and classes that implement the CompareTo method.

Reversing List

Here we see how you can reverse the order of the element collection in your List. You can use this method on an unsorted List, or you can combine this with an ascending sorting method to get a descending sort. This means you can change the ordering from A - Z to Z - A, which can be very useful.

=== Program that uses Reverse (C#) ===

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> list = new List<string>();
        list.Add("anchovy");
        list.Add("barracuda");
        list.Add("bass");
        list.Add("viperfish");

        // Reverse List in-place, no new variables required
        list.Reverse();

        foreach (string value in list)
        {
            Console.WriteLine(value);
        }
    }
}

=== Output of the program ===

viperfish
bass
barracuda
anchovy

Sorting on property

Here 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 of the program ===

nile
indus
danube
mississippi

Notes on the preceding code. 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".

See Descending Keyword.

Summary

Here we 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.

See List Examples.

See Sort Overview.

See List Overview.

© 2007-2010 Sam Allen. All rights reserved.

Dot Net Perls  Sam Allen