madlan
madlan

Reputation: 1397

Comparing two lists of custom objects

I have two generic lists that I need to compare for any additions or subtractions of entries. The lists are of a custom class that contains user connection details.

Dim ConnectedUsersOld As New List(Of ConnectedUser)
Dim ConnectedUsersNew As New List(Of ConnectedUser)

I would like to find:

a) Any ConnectedUsers that are in the ConnectedUsersNew list, that are not in the ConnectedUsersOld list. (New users for this session)

b) Any ConnectedUsers that are in the ConnectedUsersOld list, that are not in the ConnectedUsersNew list. (Users that have left since the last session)

The ConnectedUsers object has a property called username for comparing.

Upvotes: 1

Views: 1954

Answers (1)

Alex Filipovici
Alex Filipovici

Reputation: 32571

Try this:

Imports System.Linq
Imports System.Collections.Generic

Class Program
    Private Shared Sub Main(args As String())
        Dim ConnectedUsersOld As New List(Of ConnectedUser)() From { _
            New ConnectedUser() With { _
                Key .Id = 1 _
            }, _
            New ConnectedUser() With { _
                Key .Id = 2 _
            }, _
            New ConnectedUser() With { _
                Key .Id = 3 _
            } _
        }
        Dim ConnectedUsersNew As New List(Of ConnectedUser)() From { _
            New ConnectedUser() With { _
                Key .Id = 3 _
            }, _
            New ConnectedUser() With { _
                Key .Id = 4 _
            }, _
            New ConnectedUser() With { _
                Key .Id = 5 _
            } _
        }

        Dim comparer = New UserComparer()
        Dim newUsers = ConnectedUsersNew.Except(ConnectedUsersOld, comparer).ToList()
        Dim oldUsers = ConnectedUsersOld.Except(ConnectedUsersNew, comparer).ToList()
    End Sub

    Private Class ConnectedUser
        Public Property Id() As Integer
            Get
                Return m_Id
            End Get
            Set
                m_Id = Value
            End Set
        End Property
        Private m_Id As Integer
    End Class

    Private Class UserComparer
        Implements IEqualityComparer(Of ConnectedUser)

        Public Function Equals(x As ConnectedUser, y As ConnectedUser) As Boolean
            Return x.Id = y.Id
        End Function

        Public Function GetHashCode(obj As ConnectedUser) As Integer
            Return obj.Id
        End Function
    End Class
End Class

Upvotes: 1

Related Questions