我有两种方法可以对客户进行模糊搜索。一个是缩写名称,另一个是客户的全名。当我拿这两个结果集然后将它们结合在一起时(我已经读过几个地方应该删除不同的值)我得到重复。认为我需要做的就是在此调用.Distinct()
方法,我仍然会得到重复。我是否需要在客户对象中实现一些比较功能?
我的代码:
Dim shortNameMatch As List(Of ICustomer) = CustomerLibrary.GetCustomersByShortName(term)
Dim custNameMatch As List(Of ICustomer) = CustomerLibrary.GetCustomersByCustName(term)
Dim allMatch = (From a In (From s In shortNameMatch Select s).Union(From c In custNameMatch Select c) Select a).Distinct()
答案 0 :(得分:6)
您需要创建一个相等比较器,并在Union
或Distinct
中使用它:
Public Class MyComparer
Implements IEqualityComparer(Of ICustomer)
Public Overloads Function Equals(ByVal x As ICustomer, ByVal y As ICustomer) _
As Boolean Implements _
System.Collections.Generic.IEqualityComparer(Of ICustomer).Equals
Return ((x.id = y.id) AndAlso (x.title = y.title))
End Function
Public Overloads Function GetHashCode(ByVal obj As ICustomer) _
As Integer Implements _
System.Collections.Generic.IEqualityComparer(Of ICustomer).GetHashCode
Return Me.GetHashCode()
End Function
End Class
用法示例:
Dim allMatch = shortNameMatch.Union(custNameMatch).Distinct(New MyComparer())
Dim allMatch = shortNameMatch.Union(custNameMatch, New MyComparer())
答案 1 :(得分:2)
Union
将删除重复项。如果您需要应用条件其他而不是引用相等,请将IEqualityComparer<ICustomer>
传递给Union
。