Home > Back-end >  how can i delete the object kept in the list with a button
how can i delete the object kept in the list with a button

Time:10-20

public interface IPerson
    {
        int Id { get; set; }
        string FirstName { get; set; }
        string LastName { get; set; }
        string Address  { get; set; }

        
    } 




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





private void button3_Click(object sender, EventArgs e)
        {
            int b = Convert.ToInt32(comboBox1.Text);
            foreach (IPerson person in Customers)
                if (person.Id == b)
                    Customers.Remove((Customer)person);


        }

I want to delete the customer data kept in this way according to the id information selected from the combobox that appears in the visual. what should I do ?

CodePudding user response:

List<T> has a RemoveAll method that accepts a predicate:

Customers.RemoveAll( c => b == c.Id );

CodePudding user response:

First of all, you don't need to foreach an IPerson - you already know it's a customer - since you have a list of Customers, so why bother with the interface and why even specify it?

Second of all - you could remove all the items matching a pattern with RemoveAll ; code below is a bit verbose, but I will explain after.

var listOfCustomers = new List<Customer>();
listOfCustomers.Add(new Customer() { ID = 1 });
listOfCustomers.Add(new Customer() { ID = 2 });
listOfCustomers.RemoveAll(matchingCustomer => matchingCustomer.ID == 1);
Console.WriteLine(listOfCustomers.Count());

For this example I add 2 customers, Customer 1 and Customer 2 Normally I wouldn't use matchingCustomer as a term, but this is for the explanation; you tell the Lambda function: "I will use 'matchingCustomer' as the name you should be using while performing this action".

You could even chain this kind of functions, like so:

matchingCustomer.ID == id && 
matchingCustomer.Status = CustomerStatus.Active && 
matchingCustomer.SignOnDate < DateTime.Now.AddYears(-1)

So you say - the ID should be the id I got in the function, but it should also be active and at least signed on 1 year ago. (Where CustomerStatus is an enum)

  • Related