【发布时间】:2012-06-05 21:18:12
【问题描述】:
我在实现 IComparer 方法时遇到问题。 本质上,我想比较两个自定义对象的属性(属性是整数类型)。
dE 是一个 Dictionary(Of String, customObj) prTabIndex 是 customObj 的一个属性,类型为 Integer (这些适用于所有示例)
经过更多搜索,我发现this 线程建议了 3 件事:列表方法、利用 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))
...或将 lambda 函数直接合并到 SortedDictionary 的转换中:
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) “扩展方法'signature'中类型参数的数据类型作为'System.Linq.Enumerable中定义的'签名不能从这些参数中推断出来。明确指定数据类型可能会纠正这个问题错误。将鼠标悬停在“ToDictionary”上时出现。
2) 嵌套函数与委托“签名”的签名不同。在“ToDictionary”之后悬停在任何内容上时出现。
诚然,我是 lambda 函数的新手。
Q1) 我在每个实现中离我有多远?
Q2) 哪一个是计算成本最低的?为什么?
Q3) 哪一个是计算上最昂贵的?为什么?
热烈的问候,
-sf
【问题讨论】:
标签: vb.net icomparer sorteddictionary