如何在 vb.net 中使用 lambda 删除 List 的指定项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18960001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:11:15  来源:igfitidea点击:

How to delete specify items of List using lambda in vb.net

vb.netlambda

提问by frankie

Have such situation. There are two lists: list1as List(of Integer)and list2as List(of Integer).

有这样的情况。有两个列表:list1asList(of Integer)list2as List(of Integer)

I need to remove all items of list1 that are same as items of list2.

我需要删除与 list2 的项目相同的 list1 的所有项目。

For example:

例如:

list1 = 0, 1, 2, 3, 6, 10
list2 = 3, 6

After removing list2 from list1 : list1 = 0, 1, 2, 10.

从列表1删除列表2后:list1 = 0, 1, 2, 10

回答by Tim Schmelter

list1.RemoveAll(Function(i) list2.Contains(i))

or just with the delegate

或者只是与代表

list1.RemoveAll(AddressOf list2.Contains)

As noted from Meta-Knight, if list2is just a lookup list which cannot contain duplicates anyway you better use a HashSet(Of Int32)instead. It has a O(1)lookup complexity which is independend of it's size with the downside of requiring more memory if you also need list2.

正如 Meta-Knight 所指出的,如果list2只是一个不能包含重复项的查找列表,你最好使用 aHashSet(Of Int32)代替。它具有O(1)查找复杂性,这与其大小无关,但如果您还需要list2.

You can create one easily:

您可以轻松创建一个:

Dim setOfNums = new HashSet(Of Int32)(list2)
list1.RemoveAll(AddressOf setOfNums.Contains)

回答by Joel Coehoorn

list1 = list1.Except(list2).ToList();