c# - 从列表中删除最近添加的项目

标签 c# list

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/

相关文章:

c# - 内部类上的公共(public)方法与内部方法

c# - 我的注册 View 没有发布输入

python - 从元组列表创建列表

c# - 使用 C++ Baclground-Task 将解决方案部署到物理 WP8.1 设备

c# - 如何将自定义对象从异步操作过滤器传递到 ASP.net Core 中的 Controller ?

c# - SemaphoreSlim(1) 如何知道是否有其他线程在等待

list - 如何用惯用的方式编写这个函数?

list - Tcl/TK : How do I append or insert into a nested list?

python - 更改列表中的多个位置

c# - List.Insert 有任何性能损失吗?