Emily
Emily

Reputation: 17

how to check that a list contains another list item in VB.Net

I have two lists like this.

Dim List1 As IList(Of String) = New List(Of String)
Dim ListMatch As IList(Of String) = New List(Of String)

I need to figure out if List1 contains all items of ListMatch. How can i do this is VB.Net?

Upvotes: 1

Views: 2044

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460340

You can use Not SmallCollection.Except(LargeCollection).Any:

Dim containsAll = Not ListMatch.Except(List1).Any()

Documentation of Enumerable.Except:

This method returns those elements in first that do not appear in second. It does not also return those elements in second that do not appear in first.

Since Except is a set method, it doesn't take duplicates into account. So if you also want to know if List1 contains the same count of items of ListMatch you could use(less efficient):

Dim list1Lookup = List1.ToLookup(Function(str) str)
Dim listMatchLookup = ListMatch.ToLookup(Function(str) str)
Dim containsSameCount = listMatchLookup.
    All(Function(x) list1Lookup(x.Key).Count() = x.Count())

Upvotes: 3

Related Questions