multiple property sort using icompare

G

Guest

Hi,

i have seen lots of code showing how you can use the icomparer interface to
provide sorts on arrays of structures.However i want to compare two fields.
Say I have a portfolio code and asset code i would like to sort my arraylist
of class objects by asset codes within portfolios. then sorted in portfolio
order

TIA

Stu
 
C

Chris Dunaway

Your IComparer only compares two of your object instances. In the code
for the Compare, you just need to specify whether one of them is
'greater' or 'less' than the other. When you implement the Compare
function, first compare the portfolio code and only compare the asset
code if the portfolio code is the same (watch for typos):

Public Function Compare(x As Object, y As Object) As Integer
Dim obj1, obj2 As TheClass

'Code here to verify that x and y are both instances of TheClass

obj1 = DirectCast(x, TheClass)
obj2 = DirectCast(y, TheClass)

If obj1.Portfolio < obj2.Portfolio Then
Return -1
Else
If obj2.Portfolio > obj1.Portfolio Then
Return 1
Else
If obj1.Asset < obj2.Asset Then
Return -1
Else
If obj2.Asset > obj1.Asset Then
Return 1
Else
Return 0
End If
End If
End If
End If

End Function

This is code off the top of my head so watch for typos.

Chris
 
J

Jay B. Harlow [MVP - Outlook]

Stu,
As Chris suggests you need to compare both properties of both objects in the
IComparer.Compare method.

I normally use something like:

Public Class Stock
Public Portfolio As String

Public Asset As String
End Class

Public Class StockComparer
Implements IComparer

Public Function Compare(ByVal x As Object, ByVal y As Object) As
Integer Implements IComparer.Compare
Dim xStock As Stock = DirectCast(x, Stock)
Dim yStock As Stock = DirectCast(y, Stock)

If xStock.Portfolio < yStock.Portfolio Then
Return -1
ElseIf xStock.Portfolio > yStock.Portfolio Then
Return 1
ElseIf xStock.Asset < yStock.Asset Then
Return -1
ElseIf xStock.Asset > yStock.Asset Then
Return 1
Else
Return 0
End If
End Function

End Class

Which is a variation of what Chris has.

Hope this helps
Jay

| Hi,
|
| i have seen lots of code showing how you can use the icomparer interface
to
| provide sorts on arrays of structures.However i want to compare two
fields.
| Say I have a portfolio code and asset code i would like to sort my
arraylist
| of class objects by asset codes within portfolios. then sorted in
portfolio
| order
|
| TIA
|
| Stu
|
|
 

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