1

我有两个通用列表,我需要比较条目的任何添加或减去。这些列表属于包含用户连接详细信息的自定义类。

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

我想找到:

a) ConnectedUsersNew 列表中但不在 ConnectedUsersOld 列表中的任何 ConnectedUser。(本次会议的新用户)

b) ConnectedUsersOld 列表中的任何 ConnectedUser,但不在 ConnectedUsersNew 列表中。(自上次会话后离开的用户)

ConnectedUsers 对象有一个名为 username 的属性用于比较。

4

1 回答 1

1

尝试这个:

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
于 2013-08-13T13:00:13.207 回答