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.
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.
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.
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.