【问题标题】:compare two generic list containing class objects比较两个包含类对象的通用列表
【发布时间】:2010-12-21 10:32:23
【问题描述】:

如何比较我的 cSystemCatalog 类中的两个通用列表(cSystem)?我想知道列表之一是否包含更多或更少的类对象,我也想比较 _systemKey 和 _systemName

Public Class cSystemCatalog
    Private _systems As List(Of cSystem)

Public Class cSystem
    Private _systemKey As Int32
    Private _systemName As String

【问题讨论】:

    标签: .net list generics compare


    【解决方案1】:
    If _systems1.Count > _systems2.Count Then
    

    【讨论】:

    • 你的答案是正确的,但是如果我还想比较systemKey和systemName怎么办?
    【解决方案2】:
    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
    

    【讨论】:

      【解决方案3】:

      我通过实现 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多