how to use Icomparer or IComparable to sort custom class

M

Mitch

I have several classes that inherit other classes. I need to be able to sort
the Mesh class based on its inherited list of Poly.ZMax,. How do I use
IComparer or IComparable to achieve this?

Mitch.

Public Class Poly : Inherits List(Of Vector)

Private mZMax As Double

Public Sub New(ByVal f As List(Of Vector))

MyBase.AddRange(f)

mZMax = Me.Item(0).Z

For Each v As Vector In Me

If v.Z > mZMax Then

mZMax = v.Z

End If

Next

End Sub

Public ReadOnly Property PointCount()

Get

Return MyBase.Count

End Get

End Property

Public ReadOnly Property ZMax() As Double

Get

Return mZMax

End Get

End Property

End Class



Public Class Mesh : Inherits List(Of Poly)


Public Sub AddPoly(ByVal f As Poly)

MyBase.Add(f)

End Sub

Public ReadOnly Property PolyCount()

Get

Return MyBase.Count

End Get

End Property

End Class
 
F

Family Tree Mike

I believe you want Poly to impliment IComparer(of Poly), so the declaration
becomes:

Public Class Poly : Inherits List(of Vector)
Implements IComparer(Of Poly)

Then in the Poly class, include this function:


Public Function Compare(ByVal x As Poly, ByVal y As Poly) _
As Integer Implements System.Collections.Generic.IComparer(Of
Poly).Compare
If (x.ZMax < y.ZMax) Then Return -1
If (x.ZMax > y.ZMax) Then Return 1
Return 0
End Function


Now you may call MyBase.Sort() at any point necessary within your Mesh
Class.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top