Sorting in Arrays using VB.NET

In this article I will explain you about Sorting in Arrays using VB.NET.
  • 3736
Download Files:
 

As my previous article explain Reversing, and Searching of array. This article is all about the sophisticated example of using the IComparer interface and Sort function together. The IComparer interface allows you to define a Compare method in order to do a comparison between two elements of your array. This Compare method is called repeatedly by the Sort function in order to sort the array. The example given below defines a Compare method that does a comparison between two strings.

Example of Array Sorting

    ' sort an array according to the Nth element
    Imports System.Collections
        Module Module1
            Public Class CompareX
            Implements IComparer
            Private compareFrom As Integer = 0
            Public Sub New(ByVal i As Integer)
                compareFrom = i
            End Sub

            Public
Function Compare(ByVal a As Object, ByVal b As Object) As Integer Implements IComparer.Compare
                Return [String].Compare(a.ToString().Substring(compareFrom), b.ToString().Substring(compareFrom))
            End Function
            End
Class

            Public
Class ArrListEx
                Shared Sub Main(ByVal args As String())
                    Dim arr As New ArrayList()
                arr.Add(
"aaaa9999")
                arr.Add(
"bbbb8888")
                arr.Add(
"cccc7777")
                arr.Add(
"dddd6666")
                arr.Sort(
New CompareX(4))
                Dim arrList As IEnumerator = arr.GetEnumerator()
                While arrList.MoveNext()
                    Console.WriteLine("Item: {0}", arrList.Current)
                End While
                    Console.ReadLine()
                End Sub
            End
Class
        End
Module

The program in above example, has this output

saarray.gif
 

Conclusion

Hope this article would have helped you in understanding how we Using IComparer interface and sort function together in VB.NET.

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.