Search code examples
asp.netgenericssortingicomparable

Using CompareTo() to sort based on multiple columns


Currently I have an object implementing the IComparable interface (ASP.NET 3.5, VB). When I place several instantiated objects into a Generics list, I sort them by doing a simple someList.Sort. My CompareTo() function is this:

Public Function CompareTo(ByVal obj As Object) As Integer Implements 
System.IComparable.CompareTo
    'default is number of votes (opposite direction, highest first)'
    Dim sent As Sentence = CType(obj, Sentence)
    Return Not Points.CompareTo(sent.Points)
End Function

This works fine, except now I need to sort by another property, the DateSubmitted property, as a subset of the Points. For example, if three sentences have votes: 3, 1, 1, I want the one with the highest votes first (obviously) and of the two sentences with one vote, the one submitted the earliest to be listed.

Is this possible with CompareTo(), or should I just hit the database again and sort it there?

Thanks


Solution

  • Since you're on .NET 3.5, you can sort using the OrderBy extension method easily:

    Dim someSortedList = someList.OrderBy(Function(item) item.SomeColumn) _
                                 .ThenBy(Function(item) item.SomeOtherColumn)
                                 .ToList()
    
    ' OrderByDescending and ThenByDescending are also there for descending order
    

    Whether you should hit the database again or not depends on how you've retrieved data in the first place. If you have a large data set and you had retrieved only a small subset of it from the DB, then no, you should just ask the DB to grab a small subset of data based on the new sort order. Otherwise, if you already have the whole thing in memory, just sort it as I mentioned above.