Help Please - sorting array of objects

  • Thread starter Thread starter Larry
  • Start date Start date
L

Larry

Thanks for the help in advance. Does anyone have a code sample for the
following scenario.

how would you sort the array of books (BookView) by author and by price.
if there were a number of items in BookView Array?
Public BookView(0) As Book

Class Book

Public author As String
Public price As Decimal = 0

end class
 
I would implement IComparer and write my own sort algorithm. That's the
quickest way to sort on two columns. Does this head you in the right
direction, or do you want some code?

Robin S.
Ts'i mahnu uterna ot twan ot geifur hingts uto.
 
You can also let your object (Book) implement IComparable and then
rely on ArrayList.Sort to manage the sorting using the IComparable
implementation you provide.

Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim books As New System.Collections.ArrayList()
books.Add(New Book("author1", 50))
books.Add(New Book("author2", 14))
books.Add(New Book("author1", 45))
books.Add(New Book("author1", 60))
books.Add(New Book("author2", 3))
books.Add(New Book("author1", 3))
dumpbooks(books)
books.Sort()
dumpbooks(books)
End Sub

Public Sub dumpbooks(ByVal books As System.Collections.ArrayList)
For Each b As Book In books
Console.WriteLine(b)
Next
Console.WriteLine("====")
End Sub
End Class

Public Class Book
Implements IComparable

Public Sub New(ByVal author As String, ByVal price As Double)
Me.author1 = author
Me.price1 = price
End Sub 'New
Private author1 As String

Public Property Author() As String
Get
Return author1
End Get
Set(ByVal value As String)
author1 = value
End Set
End Property
Private price1 As Double

Public Property Price() As Double
Get
Return price1
End Get
Set(ByVal value As Double)
price1 = value
End Set
End Property

Public Overrides Function ToString() As String
Return author1 + " : " + price1.ToString()
End Function 'ToString


Public Function CompareTo(ByVal obj As Object) As Integer
Implements System.IComparable.CompareTo
If obj Is Nothing Then
Return 1
Else
Dim b As Book = CType(obj, Book)
Dim c As Integer = Me.Author.CompareTo(b.Author)
If c = 0 Then
Return Me.Price.CompareTo(b.Price)
Else
Return c
End If
End If

End Function
End Class

===============
Clay Burch
Syncfusion, Inc.
 
Back
Top