How do you search a generic collection to see if an object’s properties are equal?
List<Customer> = customers = GetCustomers();
Customer c = new Customer() { FirstName = "Sam" };
customers.Contains(c); //doesn't work
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You need to define “equality” for the object. You can do this several ways.
Equalsmethod ofCustomeritself, so that it uses what you think of as equality.IEqualityComparerthat you can pass into contains. Do this if you need to use different definitions of “equality” at different times, or if you don’t have the ability to modify the type.Note that any time you override
Equalsfor a type it’s important to also overrideGetHashCode, and vice versa. It’s important to ensure that any objects that are considered equal by the definition ofEqualsalso have the same hash code. It won’t matter in this particular case, but it will matter when using a hash based data structure.