gpt4 book ai didi

LINQ to Objects .Distinct() 不提取不同的对象

转载 作者:行者123 更新时间:2023-12-04 23:32:41 24 4
gpt4 key购买 nike

我有两种方法可以对客户进行模糊搜索。一种是缩写名称,另一种是客户的全名。当我获取这两个结果集然后将它们合并在一起时(我已经阅读了几个地方应该删除不同的值)我得到重复。认为我需要做的就是调用.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()

最佳答案

您需要创建一个相等比较器并在 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())

关于LINQ to Objects .Distinct() 不提取不同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2869585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com