HomeSearch

C# Sort Strings by Length

This C# example program demonstrates a way to sort strings by the Length property.

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 fast, but it should not create problems. We sort strings by their Length property.SortString Length

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

SortByLength: This method is static. It doesn't need to save state. The code uses the IEnumerable interface.

Static

Info: SortByLength receives an IEnumerable<string>, which means it can receive most collections, such as an array or List.

Var: 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
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

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
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.