VB.NET: Check if List items are equal and have same count

懵懂的女人 提交于 2019-12-24 14:19:25

问题


How can I detect whether the items of two given lists are equal?

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

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

If I compare them using SequenceEqual I get False because the order of the items is not the same. How can I compare them without sorting them first, though?

EDIT: Please take into account that this should respect duplicates, for example {1, 2, 3, 1} is not the same as {1, 2, 3} (item 1 occurs two times in the first list).


回答1:


If you want to know if both lists contain the same items you can use 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

or, with the help of HashSet(Of T):

Dim l1Set = New HashSet(Of Integer)(list1)
Dim l2Set = New HashSet(Of Integer)(list2)
bothContainSameItems = l1Set.SetEquals(l2Set)

Note that both approaches will ignore duplicates. So they will return equal for:

list1.AddRange({1, 1, 2, 3})
list2.AddRange({3, 2, 1, 3})

Here's a possible way to also check if all numbers have the same count in both lists:

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



回答2:


Also working with

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

Return Value: An IEnumerable(Of T) that contains the elements from both input sequences, excluding duplicates.




回答3:


<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

Usage:

If list1.AreItemsEqual(list2) Then
    ...


来源:https://stackoverflow.com/questions/17787538/vb-net-check-if-list-items-are-equal-and-have-same-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!