2010-08-17 114 views
0

我有一个DTO,我正在使用它来处理事务。为了确保它按正确的顺序处理,我使用iComparable并对DTO的List(T)进行排序。这很好。然而,我刚刚得到另一个要求,即客户希望以不同的顺序输出......有没有办法让我对同一个对象有两种不同的排序,或者我需要复制当前类,将输出保存为一个新类型的列表并使用该对象的新方法进行排序?看起来像一个可怕的方式来做到这一点,但找不到任何事情让我做到这一点。IComparable - 调用不同的类别?

回答

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) 
+0

完美的感谢,我有我的比较例程,但不能为我的生活得到正确的语法。 – RiddlerDev 2010-08-18 13:46:40

0

或者如果你是对的.Net 3.5或以上,你可以使用LINQ。

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