Bubble sort an array of Structure
-
I have an array of a structure similar to below: Public Structure MyStructure Public MyString as string Public MyInt1 as Int Public MyInt2 as int end structure Dim StructArray () I want a function that will sort the data by the MyString field. Any suggestions? Thanks in advance!
David Wilkes
-
I have an array of a structure similar to below: Public Structure MyStructure Public MyString as string Public MyInt1 as Int Public MyInt2 as int end structure Dim StructArray () I want a function that will sort the data by the MyString field. Any suggestions? Thanks in advance!
David Wilkes
You can use the sort method found in the Array class. You can implement IComparable in your structure. Basically this allows objects of type MyStructure to be compared. Here is a simple example.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim people As Person() = {New Person("Bob", "Smith"), New Person("Chris", "Adams")}
Array.Sort(people)
For Each p As Person In people
Console.WriteLine(p.FirstName & ":" & p.LastName)
Next
End Sub
End ClassPublic Structure Person
Implements IComparable(Of Person)Public FirstName As String Public LastName As String Public Sub New(ByVal first As String, ByVal last As String) FirstName = first LastName = last End Sub Public Function CompareTo(ByVal other As Person) As Integer Implements System.IComparable(Of Person).CompareTo Return String.Compare(Me.LastName, other.LastName) End Function
End Structure
This will sort alphabetically by the LastName field. If you want to sort in descending order you could first call sort to put them in ascending order and then call array.reverse(YourArray) to put them in descedning order. There are other ways to allow for multiple different sorts. If you want to learn more about it try looking up the interfaces Icomparer, and Icomparable.