Sort
strings, lengthIn C# programs, strings can be sorted based on their lengths. We put the shortest string
first and the longest string
last.
This method doesn't need to be fast, but it should not create problems or ever give incorrect output. We can effectively sort strings by their Length
property.
We can sort strings by the Length
property. You will see the query syntax, which uses the from and orderby
keywords. It is a complete console program that you can immediately run.
SortByLength
is static
—it doesn't need to save state. The code uses the IEnumerable
interface
.SortByLength
receives an IEnumerable
, which means it can receive most collections, such as an array or List
.var
keyword is used. A variable is created from the LINQ statement that uses query expression keywords.IEnumerable
. We can use an IEnumerable
in many ways.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; } }cat bear hyena piranha leopard stegosaurus
You can use any property on objects as the sorting key, not just Length
. For complex sorts, implementing IComparable
may be a better option.
We can sort a List
of strings by each string
's length. We use LINQ—we don't have to bother implementing IComparable
or doing anything else complicated.