Check if object exists in Generic List of class objects in C# .Net

Last Reply on Apr 02, 2014 11:43 PM By Mudassar

Posted on Apr 02, 2014 11:38 PM

i have a collections class of customers and in my register page i am adding a customer to the collection i have a List<Customer> and i want to be able to add a customer only if the Username is not the same and if it is the same i dont want to be able to add to the list how can i do this?

register class

        customer = new PreferredCustomer(firstname.Text, lastname.Text, birthdate.Text,
            address.Text, city.Text, state.Text, zipcode.Text, phonenumber.Text,
            login.Text, password.Text, commentBox.Text);
        Session["theCustomer"] = customer;
       
        Collections.PreferredCustomers.Add(customer);

 

 

 

Posted on Apr 02, 2014 11:43 PM

There is no automatic way you wiill have check whether that customer exists andif not then add.

Class

public class Customer
{
    public string Name { get; set; }
}

Code

protected void Page_Load(object sender, EventArgs e)
{
    //Add some records
    List<Customer> customers = new List<Customer>();
    customers.Add(new Customer { Name = "Mudassar" });

    //Try to add a record that exists
    string name = "Mudassar";
    if (!customers.Exists(c => c.Name == name))
    {
        customers.Add(new Customer { Name = name });
    }
}