如何在cSystemCatalog类中比较两个通用列表(cSystem)?我想知道如果其中一个列表包含更多或更少的类对象,我还想比较_systemKey和_systemName
Public Class cSystemCatalog
Private _systems As List(Of cSystem)
Public Class cSystem
Private _systemKey As Int32
Private _systemName As String
答案 0 :(得分:1)
If _systems1.Count > _systems2.Count Then
答案 1 :(得分:1)
If _systems1.Count = _systems2.Count AndAlso _
_systems1.All(Function(s1) _systems2.Any(Function(s2) _
s2._systemKey = s1._systemKey AndAlso s2._systemName = s1._systemName)) Then
如果您可以使用LINQ:
Imports System.LINQ
答案 2 :(得分:0)
我通过实现IEquatable接口找到了解决方案。
Public Class cSystem Implements IEquatable(Of cSystem)
Private _systemKey As Int32
Private _systemName As String
Public Overloads Function Equals(ByVal other As cSystem) As Boolean Implements IEquatable(Of cSystem).Equals
If other Is Nothing Then Return False
If _systemKey = other.SystemKey AndAlso _systemName = other.SystemName Then
Return True
Else
Return False
End If
End Function
Public Overrides Function Equals(ByVal obj As Object) As Boolean
If obj Is Nothing Then Return MyBase.Equals(obj)
If Not TypeOf obj Is cSystemThen
Throw New InvalidCastException("The 'obj' argument is not a cSystemobject.")
Else
Return Equals(DirectCast(obj, cSystem))
End If
End Function
Public Shared Operator =(ByVal system1 As cSystem, ByVal system2 As cSystem) As Boolean
Return system1.Equals(system2)
End Operator
Public Shared Operator <>(ByVal system1 As cSystem, ByVal system2 As cSystem) As Boolean
Return Not system1.Equals(system2)
End Operator
然后我使用列表中的contains方法来比较包含cSystem类对象的通用列表:
Dim valuesHasBeenChanged As Boolean
If objSystemCatalog.Systems.Count = objOldSystemCatalog.Systems.Count Then
For Each system As cSystem In objSystemCatalog.Systems
If objOldSystemCatalog.Systems.Contains(system) = False Then
valuesHasBeenChanged = True
End If
Next
ElseIf objSystemCatalog.Systems.Count > objOldSystemCatalog.Systems.Count Then
valuesHasBeenChanged = True
ElseIf objSystemCatalog.Systems.Count < objOldSystemCatalog.Systems.Count Then
valuesHasBeenChanged = True
End If