如何从List 中删除所有对象,其中object.variable在任何其他object.variable2中至少存在一次?

我无法弄清楚如何编写此代码。

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

谁知道我会怎么写这个?

像这样:

 list.RemoveAll(r => list.Any(o => o != r && r.ID == o.otherID)); 

一种方法是两阶段过程:

  1. 构建一必须删除的ID。
  2. 从黑名单中存在其ID的列表中删除项目。

这将需要两次通过列表。 由于添加到HashSet /测试它是否包含一个项目应该是一个恒定时间操作,整个操作应该在线性时间内运行。

 var idsToBeRemoved = new HashSet(list1.Select(item => item.otherID) .Where(otherId => otherId.HasValue)); list1.RemoveAll(item => idsToBeRemoved.Contains(item.ID)); 

编辑:更新了Id的类型为int? 在OP澄清之后。