jor
jor

Reputation: 2157

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

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).

Upvotes: 1

Views: 10326

Answers (3)

jor
jor

Reputation: 2157

<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
    ...

Upvotes: 0

Steve
Steve

Reputation: 216286

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.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460108

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

Upvotes: 6

Related Questions