You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中根据InventoryID移除List中指定的Inventory元素

解决List批量移除指定ID元素的问题

你当前调用inventories.Clear()会清空整个集合,这和你要移除所有匹配指定InventoryID的元素需求不符,以下是几种靠谱的解决方案:

1. 使用List.RemoveAll(推荐)

这是List原生提供的批量移除方法,简洁高效,内部做了优化,直接传入匹配条件即可:

// 先获取用户输入的目标InventoryID(这里假设是int类型,根据实际类型调整)
int targetId = int.Parse(Console.ReadLine());

// 移除所有InventoryId等于目标ID的元素
int removedCount = inventories.RemoveAll(inv => inv.InventoryId == targetId);

RemoveAll会返回被移除的元素数量,方便你做后续的日志或提示处理。

2. 倒序遍历移除(兼容老版本.NET)

如果你的项目基于不支持Lambda表达式的老版本.NET,可以用倒序遍历的方式避免索引异常:

int targetId = int.Parse(Console.ReadLine());

// 从集合末尾往前遍历,避免移除元素后索引错乱
for (int i = inventories.Count - 1; i >= 0; i--)
{
    if (inventories[i].InventoryId == targetId)
    {
        inventories.RemoveAt(i);
    }
}

注意不能正序遍历直接移除——正序时移除元素会导致后续元素前移,跳过部分元素。

3. LINQ筛选重新赋值

如果你需要保留原集合的副本,或者场景不允许直接修改原集合,可以用LINQ筛选出不需要移除的元素,重新生成集合:

int targetId = int.Parse(Console.ReadLine());

// 筛选出所有ID不等于目标值的元素,生成新的List
inventories = inventories.Where(inv => inv.InventoryId != targetId).ToList();

这种方式会创建新的集合实例,如果原集合被其他代码引用,需要注意引用同步问题。

内容的提问来源于stack exchange,提问作者Kokila B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:01:11