Generic List Equals

O

O.B.

I'm looking for some way to have a generic Equals operation for all
List<T> classes. In the following example, I initially thought I
could change List<CustomClass> to List<object> such that it could
handle all other types of objects. But that quickly revealed that
List<object> is not the parent of List<CustomClass>. What other
options are available?

private static bool AreListsEqual(List<CustomClass> list1,
List<CustomClass> list2)
{
bool areEqual = false;
if (list1 == null && list2 == null)
{
areEqual = true;
}
else if ((list1 != null && list2 != null) && (list1.Count ==
list2.Count))
{
// Lists are of equal size.
areEqual = true;
for (int i = 0; i < list1.Count; i++)
{
if (!list1.Equals(list2))
{
areEqual = false;
break;
}
}
}
return areEqual;
}
 
R

Rudy Velthuis

O.B. said:
I'm looking for some way to have a generic Equals operation for all
List<T> classes. In the following example, I initially thought I
could change List<CustomClass> to List<object> such that it could
handle all other types of objects. But that quickly revealed that
List<object> is not the parent of List<CustomClass>.

Indeed. Both are instantiations of List<T>, so neither is the base
class of the other.

You may want to take a look at IEqualityComparer.Default().
 
P

Pavel Minaev

I'm looking for some way to have a generic Equals operation for all
List<T> classes.  In the following example, I initially thought I
could change List<CustomClass> to List<object> such that it could
handle all other types of objects.  But that quickly revealed that
List<object> is not the parent of List<CustomClass>.  What other
options are available?

private static bool AreListsEqual(List<CustomClass> list1,
List<CustomClass> list2)

Well, if you want the operation to be generic, then surely it should
be a hint that you should look at C# generics to accomplish the task?
Just make your method generic as well:

private static bool AreListsEqual<T>(List<T> list1, List<T> list2)
{ ... }

By the way, if you want it to be truly generic, use IList<T> rather
than List<T>. Better yet, use ICollection<T>, as you really only need
Count.

Also, your code has a potential problem here:

list1.Equals(list2)

What if list1==null?

On the other hand, if you're using .NET 3.5, then just follow Peter's
advice and use the existing SequenceEquals() method. I'm not sure
whether it optimizes for IList and Count, though, or always
iterates...
 

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