C# Sort Strings by Length

Dot Net Perls

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 arranging objects
Input:

stegosaurus
dog
piranha
leopard
cat
bear
hyena

Output:

dog
cat
bear
hyena
leopard
piranha
stegosaurus

Example

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

cat
bear
hyena
piranha
leopard
stegosaurus

Description. 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.

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

LINQ (language integrated query)

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.

LINQ Examples

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.

IComparable Example With CompareTo Sort Examples