2011-05-13 66 views
1

我有一個從數據庫查詢中填充的Customers類的ObservableCollection。由於表格是如何加入的,我有時會得到一次輸入(Bill的郵寄地址不同於他的郵寄地址),兩次出現在數據中。
每個客戶行都有一個ID作爲唯一的主鍵,當有人從綁定的ListView中選擇一行時,這就是我用來提取更多客戶信息的東西。 在這個程序的WinForms版本中,我會搜索ListView中的CustomerID,如果發現我會避免再次插入它。WPF ObservableCollection中的唯一條目

ObservableCollection似乎沒有能力輕易告訴我一個CustomerID是否已經存在於一個集合的類實例中,所以我想知道處理這個問題的最好方法是什麼。

的想法我到目前爲止有:

' Not sure how to make this work, since the CustomerID and Name would be the same, but the city, state, zip might not be.' 
t = new classCustomer(CustomerID, CustomerName, City, State, Zip) 
if not sr.contains(t) then 
    sr.Add(t) 
end if 

Possibly figure out how to create an ObservableDictionary, but so far all the examples are in C#, and it may take me a while to port it over to VB.net

任何人都知道一個更好的實施?

+0

我會說這將更好地解決在查詢本身,而不是在UI – jeroenh 2011-05-13 21:20:01

+0

我會同意你,但我不知道這是多麼實際。對於高度規範化的數據庫來說,這是一個真正複雜的查詢,有10個左右的連接。我大概可以簡化查詢,但這會更好,並在更多領域有用。 – AndyD273 2011-05-15 23:19:24

回答

3

您只需告訴.NET什麼定義了一個人,在這種情況下是ID。

只需重寫equals你的客戶對象上,那麼您的收藏現在就能知道,如果2級的客戶是相同的:

Public Class Person 

    Private id As Integer 

    Public Sub New(ByVal id As Integer) 
     Me.id = id 
    End Sub 

    Public Overrides Function Equals(ByVal obj As Object) As Boolean 

     Return (TypeOf (obj) Is Person) And (DirectCast(obj, Person)).id = Me.id 

    End Function 

    Public Overrides Function GetHashCode() As Integer 
     Return Me.id.GetHashCode() 
    End Function 

End Class 




Sub Main() 

     Dim observable As New ObservableCollection(Of Person)() 

     observable.Add(New Person(1)) 

     Dim duplicate As New Person(1) 

     If Not observable.Contains(duplicate) Then 
      observable.Add(duplicate) ' never gets hit because of .Equals override 
     End If 

    End Sub 

沒有超越它不知道如何判斷它們是等價的或不。

+0

很好的回答!完美解決問題。只是好奇,讓我明白它是如何工作的,是Equals函數的GetHashCode部分,還是另一種比較方式?它只是返回id的哈希而不是整個類的哈希值,但對於Equals函數是否正常工作非常重要? – AndyD273 2011-05-16 12:55:03

+0

爲了幫助其他人需要這個改變,Equals中的obj偶爾會有類型爲「NamedObject」的類型,所以我在'If obj.GetType.Name =「Person」中添加了一些檢查然後返回(TypeOf(obj)是Person)和(DirectCast(obj,Person))。id = Me.id否則返回False End If'。在附註中,我希望他們讓你把換行符變成註釋。 – AndyD273 2011-05-16 16:41:22