Dot Net Perls
C#

Sort Strings by Length

by Sam Allen

Problem

Sort strings by length (shortest string first and longest string last, or the opposite) in .NET 3.5. This is not a hot or critical part of our code, so it doesn't need to be super fast, but it should be relatively fast and not create a problem. Let's look at some sample output first.

When our method receives this It returns this
stegosaurus
dog
piranha
leopard
cat
bear
hyena
dog
cat
bear
hyena
leopard
piranha
stegosaurus

Solution: C#

As I noted, there are many ways to solve this problem. The solution here requires LINQ, which is included in .NET 3.5. Let's take a peek at the code, and I will review it afterwards. The first example block on this page uses string arrays, and the one near the end of this post uses the List.

class TestClass
{
    public TestClass()
    {
        //
        // Initialize a list of strings.
        //
        List<string> sampleList = new List<string>
        {
            "stegosaurus",
            "pirahna",
            "leopard",
            "cat",
            "bear",
            "hyena"
        };
        //
        // Send a string array to the method.
        //
        SortByLength(sampleList.ToArray());
    }

    private static string[] SortByLength(string[] arrayIn)
    {
        //
        // Use LINQ to sort the array received and return a copy.
        //
        var sorted = from oneString in arrayIn
                     orderby oneString.Length ascending
                     select oneString;
        return sorted.ToArray();
    }
}

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. I strongly suggest learning and using LINQ as offers a whole new level of programming ease.

List Version

Many C# programmers use generics like List<string> more often, and even though they are a tiny bit slower, they work very well. Here is a version of the above function that uses generic List objects. You can put it side-by-side with the other SortByLength function, and the compiler will choose the best one for your code (method overloading).

/// <summary>
/// Sort list generics and return a copy of the List.
/// </summary>
/// <param name="listIn">The List you want to sort.</param>
/// <returns>The new sorted List.</returns>
private static List<string> SortByLength(List<string> listIn)
{
    var sorted = from oneString in listIn
                 orderby oneString.Length ascending
                 select oneString;
    return sorted.ToList();
}

Discussion

Sort your strings using LINQ for a method that is fairly fast, easy to read, and quick to type. Don't bother implementing IComparable or doing anything else complicated. Just type it out in LINQ using select, orderby, and ascending keywords. Finally, you can use any property on objects as the sorting key, not just Length.

© 2008 Sam Allen. All rights reserved.

Ads by The Lounge