List <Customer> collCustList = new List<Customer>();
我试过
if(A==B)
collCustList.Add(new Customer(99, "H", "P"));
else
collCustList.Remove(new Customer(99, "H", "P"));
但它不起作用
如何删除刚刚添加的new item(new Customer(99, "H", "P"))
?
由于
答案 0 :(得分:5)
您尝试删除新的Customer实例,而不是删除刚刚添加的Customer实例。您需要获取对第一个Customer实例的引用并将其删除,例如:
Customer customer = new Customer(99, "H", "P");
collCustList.Add(customer);
collCustList.Remove(customer);
或者,更简洁地说,如果你知道你正在删除你可能会做的最新客户:
collCustList.Remove(collCustList.Last());
如果您没有对要删除的Customer实例的现有引用,可以使用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 */);
答案 1 :(得分:3)
如果您希望此方法有效,可以使用List<T>
并Customer
实施IEquatable<Customer>
。简单的例子:
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();
}
}
答案 2 :(得分:2)
new Customer()将创建一个新实例,该实例与您添加到List中的实例不同。因此List无法匹配要删除的对象。
因此,请使用Robert建议的方式,或者您必须遍历List以匹配数据(99,“H”,“P”),然后使用匹配的客户对象的引用进行删除。
/松鸦
答案 3 :(得分:1)
Customer c = new Customer(99, "H", "P");
List collCustList = new List(); collCustList.Add(c);
collCustList.Remove(c);
这是有效的,因为它删除了添加的同一个对象。您的代码正在尝试删除另一个与您刚刚添加的对象不同的新对象(它是一个不同的对象)。
答案 4 :(得分:1)
如果您想使用Remove()
,则Customer
课程需要实施EqualityComparer.Default
答案 5 :(得分:1)
如果你想删除
private void removeButton_Click( object sender, EventArgs e )
{
if ( displayListBox.SelectedIndex != -1 )
displayListBox.Items.RemoveAt( displayListBox.SelectedIndex );
}