IComparable - 调用不同种类?

时间:2010-08-17 15:07:01

标签: vb.net sorting icomparable

我有一个用于处理交易的DTO。为了确保以正确的顺序处理,我使用iComparable并对DTO的List(of T)进行排序。这很好用。然而,我只是另外要求客户想要以不同的顺序输出...有没有办法允许我对同一个对象有两种不同的排序,或者我是否需要复制当前类,将输出保存为使用该对象的新方法对该类型和新排序的新列表?看起来像是一种糟糕的方式,但找不到任何允许我这样做的东西。

2 个答案:

答案 0 :(得分:2)

这是我从最近的一个项目中扯下的一个例子。奇迹般有效。只需要记住用适当的函数调用SORT。这超出了IComparable接口的范围,因此您可能希望从类声明中删除它。

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

然后像这样打电话给他们......

tempList.Sort(AddressOf Classes.Purchaser.CompareByGroup)

tempList.Sort(AddressOf Classes.Purchaser.CompareByName)

答案 1 :(得分:0)

如果您使用的是.Net 3.5或更高版本,也可以使用linq。

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