LINQ to Objects中的.Distinct()方法未能获取不同的对象

4

我正在使用两种方式对客户进行模糊搜索。一种是通过缩写名称,另一种是通过客户的全名。当我将这两个结果集合并在一起(根据我读过的几个地方应该会删除不同的值),我得到了重复项。我认为我只需要在此之后调用.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()
2个回答

6

您需要创建一个相等比较器并在UnionDistinct中使用它:

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())

太棒了。我以为我可能需要这样的东西,但是在任何地方都找不到它。 - Anthony Potts
或者使用morelinq的DistinctBy:http://code.google.com/p/morelinq/wiki/OperatorsOverview - TrueWill

2

Union 会移除重复项。如果您需要应用一个与引用相等性不同的条件,请将 IEqualityComparer<ICustomer> 传递给 Union


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接