简体   繁体   中英

WPF Unique Entries in an ObservableCollection

I have an ObservableCollection of class Customers that I fill from a database query. Because of how the tables are joined, I sometimes get one off entries (Bill has a shipping address that is different than his mailing address) that show up in the data twice.
Each customer row has an ID as unique primary key, and this is what I use to pull up more customer information when someone selects a row from the bound ListView. In the WinForms version of this program, I would search the ListView for the CustomerID, and if it was found I would avoid inserting it a second time.

ObservableCollection doesn't seem to have the ability to easily tell me if a CustomerID already exists in one of the class instances of the collection, so I'm wondering what the best way to handle this is.

The ideas I've had so far:

' 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

Anyone know of a better implementation?

You simply need to tell .NET what defines a person, in this case the ID.

Simply override Equals on your customer object, then your collection will now be able to know if 2 customers are equivalent:

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

without the override it does not know how to tell if they are equivalent or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM