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"))
?
谢谢
最佳答案
您尝试删除一个新的 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 */);
关于c# - 从列表中删除最近添加的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2742313/