views:

76

answers:

1

I have two objects that are derived from same the base class.

Lets say ObjA is the base class, and ClassB and ClassC inherits ObjA.

If I have a

dim lst1 as List(Of ClassB) 
dim list2 as List(Of ClassA)

and and I want to check for the existence of something being in lst1 that it is in list2, now I am only interested in comparing against one key bit of information that it is declared in the base class and is a string.

How can I iterate through the lst1 comparing against list2? I thought I could I overload/override the Equals method but I am having no joy for either of the classes and say some thing similar to

Public Overloads Overrides Function Equals(ByVal obj As Object) As Boolean
        Dim temp As ClassA = TryCast(obj, ClassA)
        If temp.Id = Me.Id Then
            Return True
        Else
            Return False
        End If
    End Function

But this doesn't seem to work.

EDIT: Further clarification. If I call

lst1.contains(instance of ClassA)

This throws an error as it (rightly) expects to get a instance of ClassB.

A: 

When you say "doesn't work"... what happens?

Overriding Equals (without overriding GetHashCode()) is a bad idea, and introduces a lot of complexity. List<T> doesn't allow you to pass in a custom IEqualityComparer<>, so IMO you should check it manually (foreach etc).

Or in .NET 3.5, LINQ; I'll give a C# example (VB isn't my strong point):

    foreach (ClassB item in list1)
    {
        bool isInSecondList = list2.Any( x=>x.Id == item.Id );
        Console.WriteLine(isInSecondList);
    }

If you are doing lots of this, or the lists are long - you may benefit from building a hash-set of the known ids first (again, a C# example - sorry):

    var ids = new HashSet<int>(list2.Select(x => x.Id));
    foreach (ClassB item in list1)
    {
        bool isInSecondList = ids.Contains(item.Id);
        Console.WriteLine(isInSecondList);
    }

This has the initial cost of hashing all the data, but may be significantly faster overall.

Marc Gravell