Computer Computer - 8 days ago 5
C# Question

List Object comparison

I am retrieving a List of customers refs storing it in a string format:

List<string> CustomerRefs(); //List of customer refs


I add a customer to the list by

List<Customer> CustomersList = new List<Customer>();

foreach (string CustRef in CustomerRefs)
{
Customer c = new Customer();
c.ref = c;
CustomersList.Add(CustRef);
}


I then want to check if we already have this customer on our database. If not then send an email.
CurrentCustomers
is a List from my DB with our current customers

foreach (Customer cm in CustomersList)
{
if (!CurrentCustomers.Contains(cm))
{
//Email someone
}
}


Now the list contains the same ref but it continues to reach
//Email someone
line.

I have some ideas on why this maybe happening, i THINK it maybe comparing the ID (which is always 0) or the entire object and against the ref which is what i am targetting.

So is there a way of comparing the ref within the object, or have i done something and finally should i instead look for customer in our database, if found, add it to the
CustomersList
and compare it this way?

Please note i have read MSDN and just need some clarification. Perhaps I've read too much into this and not seeing this clearly at the moment.

Answer

You can't use Contains because you appear to be creating separate instances of your objects even though some of them share the same ID and thus logically represent the "same" entities.

Contains is using a default equality comparer which is comparing the object references of the separate instances of Customer and failing to return true, even in cases where your Customer objects have the same ID. You need to compare the ID values. For this, you can use the Any extension method:

foreach (Customer cm in CustomersList)
{
    if (!CurrentCustomers.Any((x) => x.ID == cm.ID))
    {
        //Email someone
    }
}

The issue bespeaks a potentially bigger problem, though. You may run into issues if you have separate instances of objects that logically represent the "same" object (e.g. based on a unique ID). I would suggest maintaining only one instance of each object that is the "same". For this, you can use an Identity Map.