2010-08-17 112 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