I have a MyObject; myObjects as List(Of MyObject) and a delegate Comparison(Of MyObject) that uses a lot of comparison functions (ByA, ByB, ByC etc) à la:
Shared Function CompareMyObjectsByName(x As MyObject, y As MyObject) As Integer
Return x.Name.CompareTo(y.Name)
End Function
Now I can use
myObjects.Sort(AddressOf CompareMyObjectsByName)
How ca I use that to sort Descending or Ascending?
à la
myObjects.Sort(AddressOf CompareMyObjectsByName, ascending)
PS. Don’t say I should write 2 different comparers…
EDIT
@Jon Skeet
''' <summary>
''' Sorts a list ascensing or descending using a comparison delegate.
''' </summary>
<System.Runtime.CompilerServices.Extension()> _
Public Sub Sort(Of T)(ByVal list As List(Of T), ByVal comparison As Comparison(Of T), ByVal descending As Boolean)
If Not descending Then
list.Sort(comparison)
Else
list.Sort(???)
End If
End Sub
The simplest way is to create a
ReverseComparer(Of T)which can be constructed from an existingIComparer(Of T)and reverse the comparison. (Simply call the existing comparison with the argument order reversed – do not negate the result instead; that fails forInt32.MinValue.) I have such a class in C# already in MiscUtil, if you’re interested.Then you just need to sort by either passing in the ascending comparer, or by creating a reverse comparer from the ascending one.
EDIT: As it appears I’m not making myself clear, here’s the extension method I mean – written in C#, but it should be easy to convert it to VB:
or for a
Comparison<T>:Of course, I would usually use
OrderByandOrderByDescendingunless you really need to modify the original list…EDIT: Further note: as suggested by Konrad, you might want an enum with members
AscendingandDescendinginstead of aboolflag, just for clarity.