Oli Warner About Contact Oli on Twitter Subscribe

Sorting madness

Monday, 5 March 2007 personal vb.net

I know me whinging on about programming the site is starting to look like a recurring theme here — I promise that once I’ve got this problem out the way, that’s it for a good long while.

I’m trying to sort posts for the forums by latest activity. That bit works fine — but I also

I know me whinging on about programming the site is starting to look like a recurring theme here — I promise that once I’ve got this problem out the way, that’s it for a good long while.

I’m trying to sort posts for the forums by latest activity. That bit works fine — but I also want to take stickiness into account, in that a sticky thread should feature at the top of the first page for that section… With me? Here’s a simple example:

example thread order

The threads are Objects and they’re stored in a System.Collections.Generic.List(Of PostLink). PostLink is my “thread” Object. For the purpose of this sorting method, PostLink has a property to get the last activity and another property to determine its stickiness.

So I’ve made this comparer class:

Public Class PLForumComparer
Inherits System.Collections.Generic.Comparer(Of PostLink)

Public Overrides Function Compare(ByVal x As PostLink, ByVal y As PostLink) As Integer
If y.Sticky AndAlso Not x.Sticky Then _
Return 100000

Return y.LastReply.CompareTo(x.LastReply)
End Function
End Class

It’s junk. It half does the job and the stickies do end up in the right place half of the time… The "Return 100000" part is the real junk here… There has got to be a better method of doing this!

Update: Thanks to that wonderful god-man, Teycho (on #vb.net on dalnet), I’ve got this working code:

Public Class PLForumComparer
Inherits System.Collections.Generic.Comparer(Of PostLink)

Public Overrides Function Compare(ByVal x As PostLink, ByVal y As PostLink) As Integer
If y.Sticky = x.Sticky Then _
Return y.LastReply.CompareTo(x.LastReply)

Return y.Sticky.CompareTo(x.Sticky)
End Function
End Class

Bonza × 10∞!