Reputation: 15455
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
Upvotes: 0
Views: 71
Reputation: 16435
Overriding Equals, implementing IEqualityComparer and overriding GetHashCode is a bit of work.
If you have Resharper, you can generate these methods.
The only time I would override Equals, Implement IEqualityComparer and override GetHashCode is if I'd planned on comparing customers throughout the application. There might be some other reasons, such as sorting.
If you only comparing at a single location, the LINQ extensions give you robust set methods to find and retrieve items. I would look there before going to the trouble of overriding the Equals method.
[TestFixture]
public class ContainsTest
{
[Test]
public void TestFind()
{
var customers = new List<Customer>
{
new Customer() {FirstName = "Chuck"},
new Customer() {FirstName = Path.GetRandomFileName()},
new Customer() {FirstName = Path.GetRandomFileName()},
new Customer() {FirstName = Path.GetRandomFileName()},
new Customer() {FirstName = Path.GetRandomFileName()},
};
//Get all objects that match
var findResult = customers.Find(c => c.FirstName =="Chuck");
var findSingle = customers.Single(c => c.FirstName == "Chuck");
//Has at least one instance
customers.Any(c => c.FirstName.Contains("Chuck"));
}
public class Customer
{
public string FirstName { get; set; }
}
}
Upvotes: 1
Reputation: 203834
You need to define "equality" for the object. You can do this several ways.
Equals
method of Customer
itself, so that it uses what you think of as equality.IEqualityComparer
that 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 Equals
for a type it's important to also override GetHashCode
, and vice versa. It's important to ensure that any objects that are considered equal by the definition of Equals
also have the same hash code. It won't matter in this particular case, but it will matter when using a hash based data structure.
Upvotes: 5