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.
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.
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.
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
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 6, 2025 (edit link).