TheDeveloperBlog.com


C# Sort Strings by Length

Sort strings, length. Strings can be sorted based on their lengths. We put the shortest string first and the longest string last. This algorithm doesn't need to be super fast, but it should not create problems. We sort strings by their Length property.

Input

stegosaurus
dog
piranha
leopard
cat
bear
hyena

Output

dog
cat
bear
hyena
leopard
piranha
stegosaurus


Example. We 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 immediately run.

orderby
C# program that sorts strings by length

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

SortByLength is static. 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.

Static

And: The implicit var keyword is used. A variable is created from the LINQ statement that uses query expression keywords.

Var

Finally: The query returns another IEnumerable. We can use an IEnumerable in many ways.

IEnumerable

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

LINQ

Summary. We can sort a List of strings by each string's length. We use LINQ for a method that is 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