實施IComparer方法時遇到問題。基本上,我想比較兩個自定義對象的屬性(屬性的類型是整數)。將Dictionary轉換爲SortedDictionary後爲自定義對象實現iComparer
DE爲一個詞典(串,customObj) prTabIndex是customObj的一個屬性,是Integer類型 的(這些持有適用於所有的例子)
經過一番搜索,我發現this線程這表明3東西:一個List方法,利用LINQ,並使用一些C#3.0功能。然而,在vb中,不知道他們最好的辦法是什麼。
我已經嘗試三種不同的方式:
...我自己的滾動IComparer實現:
Public m As Sub(ByRef d As Dictionary(of String, customObj))
Dim sortedD As New SortedDictionary(Of String, customObj)(d, myCompare)
End Sub
Public Class myCompare
Implements IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
If TryCast(x, customObj).prTabIndex < TryCast(y, customObj).prTabIndex Then
Return -1
Else
Return 1
End If
End Function
End Class
...排序列表(其中,我認爲作品 - 使這個線程稍微學術)。
Dim sortedL As List(Of KeyValuePair(Of String, customObj)) = dE.ToList
sortedL.Sort(Function(firstPair As KeyValuePair(Of String, customObj), nextPair As KeyValuePair(Of String, customObj)) firstPair.Value.prTabIndex.CompareTo(nextPair.Value.prTabIndex))
...或者直接在轉換到SortedDictionary結合lambda函數:
Dim dESorted = From kvp As KeyValuePair(Of String, customObj) In dE.ToDictionary(Function(first As KeyValuePair(Of String, customObj), second As KeyValuePair(Of String, customObj)) first.Value.prTabIndex.CompareTo(nextPair.Value.prTabIndex))
注意,VS2008已強調 'dE.ToDictionary ......'(到年底根據鼠標懸停在哪裏給我兩條消息:
1)「擴展方法'簽名'中類型參數的數據類型作爲'System.Linq中定義的簽名無法從這些論證中推斷出可數發言:。顯式指定數據類型可能會更正此錯誤。在「ToDictionary」上徘徊時看到。
2)嵌套函數不具有與委託「簽名」相同的簽名。在「ToDictionary」之後徘徊在任何東西上時可以看到。
不可否認,我是lambda函數的新手。
Q1)我在每個實現中的距離有多遠? Q2)在計算上最便宜的是哪一個?爲什麼?
Q3)哪一個計算最昂貴?爲什麼?
親切問候,
-sf
忘記:然後將您的DemoClass對象添加到列表(Of DemoClass),然後使用列表(Of ...)的.Sort函數。 – SSS