如果您想知道两个列表是否包含相同的项目,您可以使用Enumerable.Except
:
Dim bothContainSameItems As Boolean
If list1.Count > list2.Count Then
bothContainSameItems = Not list1.Except(list2).Any()
Else
bothContainSameItems = Not list2.Except(list1).Any()
End If
或者,借助HashSet(Of T)
:
Dim l1Set = New HashSet(Of Integer)(list1)
Dim l2Set = New HashSet(Of Integer)(list2)
bothContainSameItems = l1Set.SetEquals(l2Set)
请注意,这两种方法都将忽略重复项。所以他们将返回equal
:
list1.AddRange({1, 1, 2, 3})
list2.AddRange({3, 2, 1, 3})
这是一种可能的方法来检查两个列表中的所有数字是否具有相同的计数:
bothContainSameItems = list1.Count = list2.Count
If bothContainSameItems Then
Dim l1Ordered = list1.OrderBy(Function(i) i).ToList()
Dim l2Ordered = list2.OrderBy(Function(i) i).ToList()
For i As Int32 = 0 To l1Ordered.Count - 1
If l1Ordered(i) <> l2Ordered(i) Then
bothContainSameItems = False
Exit For
End If
Next
End If