Don't allow an object to be added to a list(Customer>

inkedGFX

Well-known member
Joined
Feb 2, 2013
Messages
142
Programming Experience
Beginner
I have a list<Customer> and I don't want the user to add a "Customer" if the "Customer " is already in the list....I have tried

 if (Customer.Contains(businessNameTextBox.Text))
{
// process code here
}

this is as far as I get because there is an error - which is Customer doesnt contain a method for .Contains

any help would be appreciated

Thank You
InkedGFX
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,136
Location
Sydney, Australia
Programming Experience
10+
Firstly, what's a Customer? Presumably it's a class of your own definition so you might consider explaining it rather than assuming that we'll just know. Most importantly, what constitutes a Customer already being in the list? Are you talking about not allowing the same Customer object to be added twice or do you mean you don't want to add different Customer objects if they have the same value for one or more properties? You have to provide a FULL and CLEAR explanation because we have no prior knowledge of your project.

That said, as an example, if your Customer class had a CustomerName property and your requirement was that that property value had to be unique then it could look like this:
if (myCustomerList.All(c => c.CustomerName != newCustomer.CustomerName))
{
    myCustomerList.Add(newCustomer);
}
That says that you should add the new item if all existing items in the list satisfy the condition that the existing item's CustomerName is not equal to the new item's CustomerName.

You might also consider using a HashSet<Customer> instead of a List<Customer>. You can then build the knowledge of what makes a unique item into the HashSet so you can just call Add with any item and it will handle the rest.
 
Top Bottom