Remove recently added item from list

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

I tried

if(A==B)
        collCustList.Add(new Customer(99, "H", "P"));

else
        collCustList.Remove(new Customer(99, "H", "P"));

but it does not work

How can I delete the new item(new Customer(99, "H", "P"))one I just added?

thank

+3
source share
6 answers

If you want this to work, you can use List<T>and have Customerimplement IEquatable<Customer>. A simple example:

using System;
using System.Collections.Generic;

class Customer : IEquatable<Customer>
{
    public int i;
    public string c1, c2;
    public Customer(int i, string c1, string c2)
    {
        this.i = i;
        this.c1 = c1;
        this.c2 = c2;
    }

    bool System.IEquatable<Customer>.Equals(Customer o)
    {
        if(o == null)
            return false;
        return this.i == o.i &&
            this.c1 == o.c1 &&
            this.c2 == o.c2;
    }

    public override bool Equals(Object o)
    {
        return o != null && 
            this.GetType() == o.GetType() &&
            this.Equals((Customer) o);
    }

    public override int GetHashCode()
    {
        return i.GetHashCode() ^
            c1.GetHashCode() ^
            c2.GetHashCode();
    }
}
+3
source

Instead of deleting the client instance that you just added, you are trying to delete a new client instance. You will need to get a link to the first client instance and delete it, for example:

Customer customer = new Customer(99, "H", "P");
collCustList.Add(customer);
collCustList.Remove(customer);

or, more briefly, if you know that you are removing the last client you can do:

collCustList.Remove(collCustList.Last());

, , Linq :

Customer customer = collCustList.Where(c => c.Number == 99 && c.Type == "H" /* etc */).FirstOrDefault();
if (customer != null)
{
    collCustList.Remove(customer);
}

RemoveAll():

collCustList.RemoveAll(c => c.Number == 99 && c.Type == "H" /* etc */);
+5

new Customer() , , . , List .

, , , (99, "H", "P" ), .

/

+2
Customer c = new Customer(99, "H", "P");
List collCustList = new List(); collCustList.Add(c);
collCustList.Remove(c);

, , . , , ( ).

+1

Remove(), Customer EqualityComparer.Default

+1
source

If you want to delete the file

  private void removeButton_Click( object sender, EventArgs e )
      {
        if ( displayListBox.SelectedIndex != -1 )
          displayListBox.Items.RemoveAt( displayListBox.SelectedIndex );
      }
+1
source

Source: https://habr.com/ru/post/1743444/


All Articles