aardvarkm11
aardvarkm11

Reputation: 23

Comparing two complex objects

I've searched through stackoverflow and found numerous answers to comparing two complex objects in Visual Studio (specifically VB.NET), but haven't found anything suitable for me.

My object contains over 40 properties of different data types (integer, double, list of doubles, list of list of strings, etc) and other properties may be added at any time the program is updated, so using reflection to manually type out each property name is not useful for me.

Specifically this is how the two objects are organized

Obj1 = New List(of CustomClass)
Obj2 = New List(of CustomClass)

The "CustomClass" has over 40 properties such as:

Dim _Color1 as Color
Dim Prop1 as New List(of String)
Dim _Event1 as New List(of List(of String))
...

I've tried using: Obj1 Is Obj2 Object.Compare(Obj1, Obj2) Obj1.equals(Obj2)

and even though Obj1 and Obj2 contains the same values, they are still evaluating to false.

I've also tried:

For Each ObjSub as CustomClass in Obj1
    If Obj2.Contains(Obj1) = True Then

    End If
Next

But .Contains also evaluates to False even though Obj1 and Obj2 contains the same values.

Is there any way to compare only the values in Obj1 and Obj2 without having to type out all 40-ish properties?

Upvotes: 2

Views: 1816

Answers (2)

Douglas Barbin
Douglas Barbin

Reputation: 3615

Try this instead of your code:

For Each ObjSub as CustomClass in Obj1
    If Obj2.Contains(ObjSub) Then

    End If
Next

You want to see if Obj2 contains the elements of Obj1, not Obj1 itself.

Upvotes: 0

Heinzi
Heinzi

Reputation: 172270

What you are looking for is called a deep or recursive comparison. Unfortunately, there's nothing built-in in the .NET framework to do that.

This is a non-trivial task, especially if you have nested collection types. The following question list some common solutions which the C# folks have found for this problem. They might be an option for you as well, if you convert them to VB or use them as an external library:

Upvotes: 1

Related Questions