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

Met*_*uru 6 c# list

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

我有一个项目列表,这些项目都有ID.还有另一个我们称之为otherID的值.如果otherID为零或null,我们将忽略它.但是,如果otherID包含列表中另一项的ID,我想从列表中删除该项.

例:

item1.ID = 5, item1.otherID = null
item2.ID = 6, item2.otherID = 5
item3.ID = 7, item3.otherID = null
Run Code Online (Sandbox Code Playgroud)

所以应该从列表中删除item1,因为它的ID存在于item2的otherID字段中

谁知道我会怎么写这个?

Ani*_*Ani 11

一种方法是两阶段过程:

  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));
Run Code Online (Sandbox Code Playgroud)

编辑:在OP澄清后更新了Id类型int?.


SLa*_*aks 8

像这样:

list.RemoveAll(r => list.Any(o => o != r && r.ID == o.otherID));
Run Code Online (Sandbox Code Playgroud)