Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sort by multiple properties

Status
Not open for further replies.

dragonwell

Programmer
Oct 21, 2002
863
US
I have a class that needs to implement IComparable. I want to do a multi-field sort, such as a SQL "order by" clause (select * from person order by name, age). So say my class Person has a Name string and an Age int, what would the CompareTo method look like?

Code:
Public Function CompareTo(ByVal other As Person) As Integer Implements System.IComparable(Of Person).CompareTo

'sort by name... ok		
Return other.Name.CompareTo(Me.Name)

'sort by age... ok
Return other.Age.CompareTo(Me.Age)

'how to do both???

	End Function



[blue]_______________________________________[/blue]
Business Logic:"AND when tweetle beetles battle with paddles in a puddle, they call it a tweetle beetle puddle paddle battle AND..." - Dr. Suess
 
OK, I think I got it. Anyone see any problems?
Code:
Public Function CompareTo(ByVal other As Person) As Integer Implements System.IComparable(Of Person).CompareTo

		If Name.CompareTo(other.Name) = 0 Then
			Return Me.Age.CompareTo(other.Age)
		Else
			Return Me.Name.CompareTo(other.Name)
		End If

	End Function

[blue]_______________________________________[/blue]
Business Logic:"AND when tweetle beetles battle with paddles in a puddle, they call it a tweetle beetle puddle paddle battle AND..." - Dr. Suess
 
Yep looks fine by me.

but a simple (perhaps not that simple) nunit testCase would show you how good it really is.

Christiaan Baes
Belgium

"My new site" - Me
 
or you could do it in one line

Code:
Public Function CompareTo(ByVal other As Person) As Integer Implements System.IComparable(Of Person).CompareTo
    Return (Me.Name & " " & me.Age.toString("0000")).toString.CompareTo((other.Name & " " & other.Age.toString("0000")).toString)
        End If
    End Function

I'm not sure about the format of the int in the tostring. And I would prefer to use the private variable instead of the properties.


Christiaan Baes
Belgium

"My new site" - Me
 
Ah, good idea. The key is using toString("0000") on the integer.

[blue]_______________________________________[/blue]
Business Logic:"AND when tweetle beetles battle with paddles in a puddle, they call it a tweetle beetle puddle paddle battle AND..." - Dr. Suess
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top