LINQ to Objects.Distinct()不提取不同的对象 [英] LINQ to Objects .Distinct() not pulling distinct objects

查看:134
本文介绍了LINQ to Objects.Distinct()不提取不同的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种方式对客户进行模糊搜索.一种是缩写名称,另一种是客户的全名.当我将这两个结果集合并在一起时(我读过几个地方应该删除不同的值),我得到了重复项.认为我需要做的就是在此上调用.Distinct()方法,我仍然会得到重复的内容.我是否需要在客户对象中实现一些比较功能? 我的代码:

I have two ways that I am doing a fuzzy search for a customer. One is by an abbreviated name and the other is by the customer's full name. When I take these two result sets and then union them together (which I have read several places should remove distinct values) I get duplicates. Thinking that all I need to do is then call the .Distinct() method on this, I also still get duplicates. Do I need to implement some compare functionality in my customer object? My code:

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

推荐答案

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

You need to create an equality comparer and use it in the Union or 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())

这篇关于LINQ to Objects.Distinct()不提取不同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆