Sort Strings by LengthSort strings by the Length property. Use an orderby query expression.
This page was last reviewed on Apr 3, 2023.
Sort strings, length. In C# programs, strings can be sorted based on their lengths. We put the shortest string first and the longest string last.
Shows a property
C# algorithm notes. This algorithm 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.
String Length
An example. 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.
Note SortByLength is static—it doesn't need to save state. The code uses the IEnumerable interface.
Note 2 SortByLength receives an IEnumerable, which means it can receive most collections, such as an array or List.
Tip The implicit var keyword is used. A variable is created from the LINQ statement that uses query expression keywords.
Finally The query returns another IEnumerable. We can use an IEnumerable in many ways.
Shows a property
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
LINQ syntax. The C# language supports query expressions, and they have the "from" keyword. The example uses this syntax—it is the clearest to understand.
Other properties. You can use any property on objects as the sorting key, not just Length. For complex sorts, implementing IComparable may be a better option.
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 3, 2023 (edit).
© 2007-2024 Sam Allen.