我无法弄清楚如何编写此代码.
我有一个项目列表,这些项目都有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字段中
谁知道我会怎么写这个?
Ani*_*Ani 11
一种方法是两阶段过程:
这将需要两次通过列表.由于添加到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?.
像这样:
list.RemoveAll(r => list.Any(o => o != r && r.ID == o.otherID));
| 归档时间: | 
 | 
| 查看次数: | 3704 次 | 
| 最近记录: |