使用一个列表<>从另一个列表<>中删除条目

时间:2016-09-15 16:34:17

标签: c# list

我有两个列表,有一个共同元素

List<myObject> myObj (contains ID, name, other stuff)
1, Dave, stuff
2, Albert, stuff
10, James, stuff
15, Rita, stuff

List<int> myID (contains ID)
2,
10

我需要做的是删除myObj中的任何条目,其中myObj.ID位于myID.ID

(请记住,对于真实代码,两个列表都要长得多)

1 个答案:

答案 0 :(得分:6)

从ID列表中创建HashSet<int>以进行快速查找,然后使用RemoveAll方法:

var idSet = new HashSet<int>(myID);
myObj.RemoveAll(item => idSet.Contains(item.ID));