How to Sort and Reverse of Array in VB.NET

You can sort arrays by including a static method in the Array class called Sort() and Reverse a string using the ToCharArray function, the Array.Reverse subroutine, and then the String constructor.
  • 5499

Arrays are generally used for storing similar types of values or objects. They allow grouping variables together and allow referring to them by using an index. When you set up an array with the Dim word, you put the name of your array variable, and tell Visual Basic how many items you want to store in the array. But you need to use parentheses around your figure.

When declaring and initialising arrays in the same statement, you must specify the type of the array elements and the number of the elements the array will hold. In VB.NET, arrays are zero based, which means that the index of the first element is zero.

Sort An Array

You can sort arrays by including a static method in the Array class called Sort(). In its simplest form the Sort() method accepts a single input parameter - the one-dimensional array to sort - and sorts the array. If the array's elements are of a type that implements the IComparable interface, then sorting the arrays is as simple as calling Array.Sort(ArrayName).

Reverse An Array

In the VB.NET language, you can reverse a string using the ToCharArray function, the Array.Reverse subroutine, and then the String constructor. Note: Strings in VB.NET cannot be manipulated directly; instead, you must convert them to character arrays with the ToCharArray function.

Example

Imports System
 
Public Class MainClass
 
    Shared Sub Main()
        Dim alphaArray As [String]() = {"A""Z""B""M"}
 
        Console.WriteLine("Given Alphabets:")
        printArray(alphaArray)

        Console.WriteLine("Reversed Alphabets:")
        Array.Reverse(alphaArray)
        printArray(alphaArray)
 
        Dim alphaArray1 As [String]() = {"e""l""s""T""o""B""f""v"}
 
        Console.WriteLine("Unsorted Alphabets:")
        printArray(alphaArray1)
 
        Console.WriteLine("Sorted Alphabets:")
        Array.Sort(alphaArray1)
        printArray(alphaArray1)
        Console.ReadLine()
 
    End Sub
    Public Shared Sub printArray(ByVal A() As Object)
        Dim obj As Object
        For Each obj In A
            Console.WriteLine("Value: {0}", obj)
        Next obj
        Console.WriteLine(ControlChars.Lf)
    End Sub
 
End Class

Output

array1.gif

Categories

More Articles

© 2013 dotNetheaven. All rights reserved.