我不知道如何编写这段代码。
我有一个项目列表,所有项目都有一个 ID。还有另一个值,我们称之为 otherID。如果 otherID 为零或 null,我们将忽略它。但是,如果 otherID 包含列表中另一个项目的 ID,我想从列表中删除该项目。
例子:
item1.ID = 5, item1.otherID = null
item2.ID = 6, item2.otherID = 5
item3.ID = 7, item3.otherID = null
所以 item1 应该从列表中删除,因为它的 ID 存在于 item2 的 otherID 字段中
有人知道我会怎么写吗?
最佳答案
执行此操作的一种方法是分两步进行:
- 构建一组必须删除的 ID。
- 从列表中删除其 ID 在黑名单中的项目。
这将需要两次传递列表。由于添加到 HashSet/测试它是否包含一个项目应该是一个常量时间操作,所以整个操作应该在线性时间内运行。
var idsToBeRemoved = new HashSet<int?>(list1.Select(item => item.otherID)
.Where(otherId => otherId.HasValue));
list1.RemoveAll(item => idsToBeRemoved.Contains(item.ID));
编辑:在 OP 澄清后,将 Id
的类型更新为 int?
。
关于c# - 如何从 List<object> 中删除所有对象,其中 object.variable 在任何其他 object.variable2 中至少存在一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4037634/