1

如何检测两个给定列表的项目是否相等?

Dim list1 As New List(Of Integer)
list1.AddRange({1, 2, 3})

Dim list2 As New List(Of Integer)
list2.AddRange({3, 2, 1})

如果我比较它们,SequenceEqual我会得到False,因为项目的顺序不一样。但是,如何在不先对它们进行排序的情况下比较它们呢?

编辑:请考虑到这应该尊重重复,例如{1, 2, 3, 1}{1, 2, 3}(项目1在第一个列表中出现两次)不同。

4

3 回答 3

5

如果您想知道两个列表是否包含相同的项目,您可以使用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
于 2013-07-22T12:30:25.770 回答
1

还与

Dim list1 As New List(Of Integer)
list1.AddRange({1, 2, 3})

Dim list2 As New List(Of Integer)
list2.AddRange({3, 2, 1})

Dim list3 = list1.Union(list2)
if list3.OrderBy(Function(i) i).SequenceEqual(list1.OrderBy(Function(i) i)) then
    Console.WriteLine("Equal")
else
    Console.WriteLine("Not Equal")
end if

IEnumerable.Union

返回值:一个 IEnumerable(Of T),包含来自两个输入序列的元素,不包括重复项。

于 2013-07-22T12:33:15.093 回答
0
<System.Runtime.CompilerServices.Extension()> _
Function AreItemsEqual(Of T)(col1 As IEnumerable(Of T), col2 As IEnumerable(Of T)) As Boolean
    ' performance checks
    If col1 Is col2 Then Return True
    If col1 Is Nothing OrElse col2 Is Nothing Then Return False
    If col1.Count <> col2.Count Then Return False
    ' compare their elements
    Dim o1 As IEnumerable(Of T) = col1.OrderBy(Function(i) i)
    Dim o2 As IEnumerable(Of T) = col2.OrderBy(Function(i) i)
    Return o1.SequenceEqual(o2)
End Function

用法:

If list1.AreItemsEqual(list2) Then
    ...
于 2013-07-22T13:09:32.747 回答