我有两个通用列表,我需要比较条目的任何添加或减少。 这些列表是一个包含用户连接详细信息的自定义类。
Dim ConnectedUsersOld As New List(Of ConnectedUser)
Dim ConnectedUsersNew As New List(Of ConnectedUser)
我想找到:
a)ConnectedUsersNew列表中的任何ConnectedUsers,它们不在ConnectedUsersOld列表中。 (此会话的新用户)
b)ConnectedUsersOld列表中的任何ConnectedUsers,它们不在ConnectedUsersNew列表中。 (自上次会话以来已离开的用户)
ConnectedUsers对象有一个名为username的属性用于比较。
答案 0 :(得分: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