开发者

IComparable - Call different sorts?

开发者 https://www.devze.com 2023-01-12 10:41 出处:网络
I have a DTO that I am using to process transactions. To ensure that it is processing in the correct order, I am using iComparable and sorting the List(of T) of the DTO. That works great. However I ju

I have a DTO that I am using to process transactions. To ensure that it is processing in the correct order, I am using iComparable and sorting the List(of T) of the DTO. That works great. However I just got another requirement that the customer wants the output in a different order... is there a way to allo开发者_StackOverfloww me to have two different sorts for the same object, or do I need to copy the current class, save the output as a new List of that type and sort using the new way for that object? Seems like an awful way to do it, but cannot find anything that allows me to do it.


Here is an example I ripped from a recent project. Works like a charm. Just have to remember to call SORT with the appropriate function. This is outside the scope fo the IComparable interface, so you might want to drop that from your class declaration.

Public Class Purchaser
....
Public Shared Function CompareByGroup( _
   ByVal x As Purchaser, ByVal y As Purchaser) As Integer

   If x Is Nothing Then
     If y Is Nothing Then
       ' If x is Nothing and y is Nothing, they're equal. 
       Return 0
     Else
       ' If x is Nothing and y is not Nothing, y is greater. 
       Return -1
     End If
   Else
     If y Is Nothing Then
       ' If x is not Nothing and y is Nothing, x is greater. 
       Return 1
     Else
       ' ...and y is not Nothing, compare by GroupName.
       Return x.GroupName.CompareTo(y.GroupName)
     End If
    End If
  End Function

  Public Shared Function CompareByName( _
    ByVal x As Purchaser, ByVal y As Purchaser) As Integer

    ... 'you get the idea
  End Function

And call them like this...

tempList.Sort(AddressOf Classes.Purchaser.CompareByGroup)

or

tempList.Sort(AddressOf Classes.Purchaser.CompareByName)


Or you can use linq if you are on .Net 3.5 or above.

dim orderedlistofdtos = (from e in listofdtos order by e.whatever select e).Tolist
0

精彩评论

暂无评论...
验证码 换一张
取 消