我有一个用于处理事务的 DTO。为了确保它以正确的顺序处理,我使用 iComparable 并对 DTO 的 List(of T) 进行排序。这很好用。但是我刚刚得到另一个要求,客户希望以不同的顺序输出......有没有办法让我对同一个对象有两种不同的排序,或者我是否需要复制当前类,将输出另存为该类型的新列表并使用该对象的新方式进行排序?似乎是一种糟糕的方法,但找不到任何可以让我这样做的方法。
问问题
336 次
2 回答
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)
于 2010-08-17T16:58:14.723 回答
0
或者,如果您使用 .Net 3.5 或更高版本,则可以使用 linq。
dim orderedlistofdtos = (from e in listofdtos order by e.whatever select e).Tolist
于 2010-08-17T18:34:17.843 回答