gpt4 book ai didi

c# - 如何从 List 中删除所有对象,其中 object.variable 在任何其他 object.variable2 中至少存在一次?
转载 作者:太空狗 更新时间:2023-10-29 20:50:53 25 4
gpt4 key购买 nike

我不知道如何编写这段代码。

我有一个项目列表,所有项目都有一个 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 字段中

有人知道我会怎么写吗?

最佳答案

执行此操作的一种方法是分两步进行:

  1. 构建一组必须删除的 ID
  2. 从列表中删除其 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/

25 4 0