Equality Test For Objects

N

Nathan Sokalski

I have two objects that I need to compare the values of. The declaration of
the object is:

Dim mylist As New Collections.Generic.List(Of Integer)

How can I compare the values of the Integers in the List? Thanks.
 
J

Jack Jackson

I have two objects that I need to compare the values of. The declaration of
the object is:

Dim mylist As New Collections.Generic.List(Of Integer)

How can I compare the values of the Integers in the List? Thanks.

First you need to define what equality means.

If one list contains: 5, 9, 2
and the other contains: 2, 5, 9

are the lists equal?
 
N

Nathan Sokalski

I guess that's a good point in the case of some objects. In my case, because
I am comparing Lists, they would be equal.
 
N

Nathan Sokalski

I do have two objects, I just posted the declaration for one because both
objects have the same declaration (well, other than the name). Sorry about
that. I want to compare them to the other List, basically meaning I want to
make sure both Lists contain the same values. I think that in my case
Enumerable.SequenceEqual() will work, although it would be nice to have a
similar method that does not care about the order of the elements. Thanks.

Also, and this question is a little bit less urgent, but is there a way to
do the same thing for an array of Lists, such as the following:

Dim mylist(4) As New Collections.Generic.List(Of Integer)
Dim mylist2(4) As New Collections.Generic.List(Of Integer)

In my case, I can obviously just call Enumerable.SequenceEqual() for each
index to create a Boolean expression, since my arrays are a small fixed
size, but in the case of larger or variable sized arrays, this would require
a loop or function. Is there a way to do this for arrays without using a
loop or function? Thanks again.
 
C

Cor Ligthert[MVP]

Peter,

I think you are right but why not

\\\VB10 code
Dim lst1 As New List(Of Integer) From {1, 2, 3, 4}
Dim lst2 As New List(Of Integer) From {1, 2, 3, 5}
For i = 0 To lst1.Count - 1
If lst1(i) <> lst2(i) Then MessageBox.Show((i + 1).ToString)
Exit For
Next
///
In VB9 the demo list part has to be initialized with two extra lines

Cor
 
V

vanderghast

If the order of the elements is irrelevant , ie { 1 2 3} is considered
equal to { 1 3 2} (ie, you are using SETS, or some data collection where
position in the list is irrelevant),

order (sort) the two lists, than use SequenceEqual.


return seqence1.OrderBy(i=>i).SequenceEqual(sequence2.OrderBy(i=>i));





Vanderghast, Access MVP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top