Sort strings, length. How can we sort an array of strings in VB.NET by their lengths? This is more complex than a alphabetical sort—we must specifically sort on the Length property.
With the LINQ extensions to the language, we can use a query expression for this sort method. And with a method like ToArray we can convert the result into an array.
Example. This program starts with an array of unsorted Strings. The strings have varying lengths, and they are not ordered by their lengths.
Part 1 We create the array of Strings. We have 7 elements in the array, and the lengths are different for most of the strings.
Part 2 This is the query expression. It returns an IOrderedEnumerable (like all Order By queries). Ascending means low to high.
Part 3 If we need to have an array from the query expression, we can call ToArray on the query expression result.
Part 4 The strings are now sorted by their lengths from low to high. The 2 strings with the same lengths retain their original order.
Module Module1
Sub Main()
' Part 1: an array of unsorted strings with different lengths.
Dim animals() = { "stegosaurus",
"piranha",
"leopard",
"cat",
"bear",
"hyena" }
' Part 2: sort strings in array from shortest to longest (Ascending).
Dim result = From a In animals
Order By a.Length Ascending
' Part 3: get array from sorted strings.
Dim resultArray = result.ToArray()
Console.WriteLine("Sorted array length: {0}", resultArray.Length)
' Part 4: print sorted strings.
For Each animal in result
Console.WriteLine(animal)
Next
End Sub
End ModuleSorted array length: 6
cat
bear
hyena
piranha
leopard
stegosaurus
Summary. With LINQ we have a way to sort collections without writing complex comparison functions. Instead we can just specify a single query, and call ToArray afterwards if needed.
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.