Ant*_*tts 4 linq union distinct
我有两种方法可以对客户进行模糊搜索.一个是缩写名称,另一个是客户的全名.当我拿这两个结果集然后将它们结合在一起时(我已经读过几个地方应该删除不同的值)我得到重复.认为我需要做的就是调用这个.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()
Run Code Online (Sandbox Code Playgroud)
您需要创建一个相等比较器并在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
Run Code Online (Sandbox Code Playgroud)
用法示例:
Dim allMatch = shortNameMatch.Union(custNameMatch).Distinct(New MyComparer())
Dim allMatch = shortNameMatch.Union(custNameMatch, New MyComparer())
Run Code Online (Sandbox Code Playgroud)