Sort strings by the Length property. Use an orderby query expression.
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.
C# program that sorts strings by length
static void Main()
// Initialize a List of strings.
List<string> sampleList = new List<string>
// Send the List to the method.
foreach (string s in SortByLength(sampleList))
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
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.