compare two generic list containing class objects
How do i compare two generic list(of cSystem) in my cSystemCatalog class? I wanna know if one of the list contains more or fewer class objects, I als开发者_开发百科o want to compare _systemKey and _systemName
Public Class cSystemCatalog
Private _systems As List(Of cSystem)
Public Class cSystem
Private _systemKey As Int32
Private _systemName As String
If _systems1.Count > _systems2.Count Then
If _systems1.Count = _systems2.Count AndAlso _
_systems1.All(Function(s1) _systems2.Any(Function(s2) _
s2._systemKey = s1._systemKey AndAlso s2._systemName = s1._systemName)) Then
Provided you can use LINQ:
Imports System.LINQ
I found a solution by implementing the IEquatable interface.
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
Then i use the contains method on the list to compare the generic lists containing cSystem class objects:
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
精彩评论