2010-05-19 44 views
4

我有兩種方法可以爲客戶進行模糊搜索。一個是縮寫名稱,另一個是客戶的全名。當我將這兩個結果集合並在一起時(我已經閱讀了幾個地方應該刪除不同的值),我得到了重複。考慮到我需要做的就是調用.Distinct()方法,我仍然會得到重複。我是否需要在客戶對象中實現一些比較功能? 我的代碼:LINQ to Objects .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() 

回答

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

震撼。以爲我可能需要這樣的東西,但無法在任何地方找到它。 – 2010-05-19 22:00:25

+0

或使用morelinq的DistinctBy:http://code.google.com/p/morelinq/wiki/OperatorsOverview – TrueWill 2010-12-02 23:31:39

2

Union將刪除重複。如果您需要應用條件其他而不是參考相等,請將IEqualityComparer<ICustomer>傳遞到Union