Sort
strings, lengthHow 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.
This program starts with an array of unsorted Strings. The strings have varying lengths, and they are not ordered by their lengths.
IOrderedEnumerable
(like all Order By
queries). Ascending means low to high.ToArray
on the query expression result.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
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.