C# Sort Strings by Length

You need to sort strings by length, putting the shortest string first and longest string last. This is not a bottleneck your code, so it doesn't need to be super fast, but it should be relatively fast and not create problems. Here we look at how you can sort strings by their Length property using LINQ and the C# language.

Arrow that indicates sorting objects
Input:  stegosaurus
        dog
        piranha
        leopard
        cat
        bear
        hyena
Output: dog
        cat
        bear
        hyena
        leopard
        piranha
        stegosaurus

Sorting strings by length

Here we look at how you can sort strings by the Length property using the LINQ extension to the C# language. You will see the query syntax, which uses the where and orderby keywords. It is a complete console program that you can run immediately.

=== Program that sorts strings by length (C#) ===

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // Initialize a List of strings.
        List<string> sampleList = new List<string>
        {
            "stegosaurus",
            "piranha",
            "leopard",
            "cat",
            "bear",
            "hyena"
        };
        // Send the List to the method.
        foreach (string s in SortByLength(sampleList))
        {
            Console.WriteLine(s);
        }
    }

    static IEnumerable<string> SortByLength(IEnumerable<string> e)
    {
        // Use LINQ to sort the array received and return a copy.
        var sorted = from s in e
                     orderby s.Length ascending
                     select s;
        return sorted;
    }
}

=== Output of the program ===

cat
bear
hyena
piranha
leopard
stegosaurus

Description of the example. SortByLength is static. This method is static because it doesn't need to save state. The code above uses IEnumerable interface. SortByLength receives an IEnumerable<string>, which means it can receive most collections, such as an array or List.

Note on the syntax used. The implicit var keyword is used. A variable is created from the LINQ statement that uses query expression keywords. The query returns another IEnumerable.

Understanding LINQ syntax. The syntax in the var statement are functional programming but are equivalent to writing the code out long-hand. My example uses this syntax because I feel it is easily the clearest to understand.

Summary

Here we saw how you can easily sort a List of strings by each string's length. Sort your strings using LINQ for a method that is fairly fast, easy to read, and quick to type. You don't have to bother implementing IComparable or doing anything else complicated. Finally, you can use any property on objects as the sorting key, not just Length.

See Sort Overview.

© 2007-2010 Sam Allen. All rights reserved.

Dot Net Perls  Sam Allen