Contains method dosen't work on BindingList<T>

G

Guest

Hi,

I have a BindingList<T> collection and I am adding concrete object T in to
the binding list. Before adding them, I want to verify if object with same
data exist in the collection. When I use Binding list’s Contain method to
check if object exist in the collection, it always returns false. Is there a
way to achieve this? I have tried implementing IComparable interface on my
concrete class, but getting same result.

Code sample:

BindingList<User> uBL=new BindingList<User>();

User u=new User();
u.FirstName=â€TTTâ€;
u.LastName=â€CCCâ€;
if (! uBL.Contains(u)) //this always returns false
{
uBL.Add(u)
}

Public class User{

Public string FirstName=string.empty;
Public string LastName=string.empty;
Public User(){}

}


Thanks
Hiten
 
M

Marc Gravell

Yes it does...

First : your example made work tricker for people than need be, as it
doesn't actually illustrate the problem; in particular, note that
BindingList<T> automatically supports referential equality, so .Add(u)
followed by .Contains(u) will always return true (for reference types). Also
your code didn't compile "as is".

However - gripes aside, the answer is to implement IEquatable<T>, which
BindingList<T> can use to check if any two objects (with different
references) are "equal".

Code below; hope this helps,

Marc

class Program {
static void Main(string[] args) {
BindingList<User> uBL = new BindingList<User>();
User u = new User("TTT","CCC");
uBL.Add(u);
Console.WriteLine(uBL.Contains(u));
User u2 = new User("TTT","CCC");
Console.WriteLine(uBL.Contains(u2));
}


}



public class User : IEquatable<User> {

public string FirstName = string.Empty;
public string LastName = string.Empty;
public User(string firstName, string lastName) {
FirstName = firstName;
LastName = lastName;
}

public bool Equals(User other) {
return FirstName == other.FirstName && LastName ==
other.LastName;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top