Saif Khan
Saif Khan

Reputation: 18792

Collection .Contains() not working

I've check everywhere and can't find a solution. I have the following

Dim users as New List(of TUser)

Private Sub AddSelectedUsers()

For Each user as TUser in gridSelectedItems()

If Not users.Contains(user) Then

users.Add(user)

End If

Next

End Sub 

The "Contains" is not working. I keep getting duplicates on the users list.

Upvotes: 1

Views: 2993

Answers (1)

Alex
Alex

Reputation: 586

The List.Contains() method uses the default equality operator. Since TUser appears to be a class, List.Contains() will only match if you are referencing the exact same instance of TUser in both comparisons, apparently isn't the case. See a more detailed explanation here.

The solution is to implement an equality override for the TUser class, as per the example here.

Upvotes: 5

Related Questions