实现 IEquatable 获取不同的对象
Implement IEquatable Get distinct objects
这对我不起作用。在花了太多时间后,我无法在 MSDN 或其他地方找到答案。我错过了什么?
Public Class PrinterInfo
Implements IEquatable(Of PrinterInfo)
Public PrinterName As String
Public PrinterDesc As String
'default equality comparer for class vb.net
Public Overloads Function Equals(ByVal other As PrinterInfo) As Boolean _
Implements IEquatable(Of PrinterInfo).Equals
Return other.PrinterName = Me.PrinterName
End Function
End Class
Public ReadOnly Property PrinterInfoList(ByVal Normal As NormalCopier) As List(Of PrinterInfo)
Get
Dim pList1 As List(Of PrinterInfo) = GetList
pList1.Sort()
Return pList1.Distinct.ToList
End Get
End Property
我得到了列表,但我只想要不同的项目。我试图实现一个相等比较器,但它不起作用。我得到了多个重复项。我需要做什么才能只获得不同的值?
MSDN: Enumerable.Distinct(Of TSource)
MSDN: IEqualityComparer(Of T) Interface
This seems similar but I don't understand it
如果可以的话,我想避免使用 Linq GroupBy。这对我来说似乎很笨拙。
Enumerable.Distinct(Of Source) 的文档说:
The default equality comparer, Default
, is used to compare values of the types that implement the IEquatable<T>
generic interface. To compare a custom data type, you need to implement this interface and provide your own GetHashCode
and Equals
methods for the type.
这就是你遗漏的部分。您需要在 class 中提供 GetHashCode()
实现。如果您查看给出的代码示例,您也会在那里看到它。当您考虑它时,它是有道理的。 Distinct
的实现在内部使用哈希集,因此自然需要适当的 GetHashCode
实现才能正常运行。
对于您的情况,请尝试将此添加到您的 PrinterInfo
class:
Public Overrides Function GetHashCode() As Integer
Return Me.PrinterName.GetHashCode()
End Function
这对我不起作用。在花了太多时间后,我无法在 MSDN 或其他地方找到答案。我错过了什么?
Public Class PrinterInfo
Implements IEquatable(Of PrinterInfo)
Public PrinterName As String
Public PrinterDesc As String
'default equality comparer for class vb.net
Public Overloads Function Equals(ByVal other As PrinterInfo) As Boolean _
Implements IEquatable(Of PrinterInfo).Equals
Return other.PrinterName = Me.PrinterName
End Function
End Class
Public ReadOnly Property PrinterInfoList(ByVal Normal As NormalCopier) As List(Of PrinterInfo)
Get
Dim pList1 As List(Of PrinterInfo) = GetList
pList1.Sort()
Return pList1.Distinct.ToList
End Get
End Property
我得到了列表,但我只想要不同的项目。我试图实现一个相等比较器,但它不起作用。我得到了多个重复项。我需要做什么才能只获得不同的值?
MSDN: Enumerable.Distinct(Of TSource)
MSDN: IEqualityComparer(Of T) Interface
This seems similar but I don't understand it
如果可以的话,我想避免使用 Linq GroupBy。这对我来说似乎很笨拙。
Enumerable.Distinct(Of Source) 的文档说:
The default equality comparer,
Default
, is used to compare values of the types that implement theIEquatable<T>
generic interface. To compare a custom data type, you need to implement this interface and provide your ownGetHashCode
andEquals
methods for the type.
这就是你遗漏的部分。您需要在 class 中提供 GetHashCode()
实现。如果您查看给出的代码示例,您也会在那里看到它。当您考虑它时,它是有道理的。 Distinct
的实现在内部使用哈希集,因此自然需要适当的 GetHashCode
实现才能正常运行。
对于您的情况,请尝试将此添加到您的 PrinterInfo
class:
Public Overrides Function GetHashCode() As Integer
Return Me.PrinterName.GetHashCode()
End Function