Search code examples
c#linqintersect

c# Intersect 2 lists with same but non identical objects


I want to intersect 2 lists of objects which have the same types and same properties in it, but the objects in the list got instantiated separatly.

class foo
{ 
  int id;
  string name;

  public foo(int Id, string Name)
  {
     id = Id;
     name = Name;
  }
}
List<foo> listA = new List<foo>() {new foo(1, "A"), new foo(2, "B"), new foo(3, "C")};
List<foo> listB = new List<foo>() {new foo(2, "B"), new foo(3, "C"), new foo(4, "D")};

List<foo> intersect = listA.Intersect(listB).ToList();

foo object B & C are both in listA & listB but when I intersect them I get 0 entrys. I know its because there are not the same object but what do I need to do to get a list with B and C anyways?. What am I missing?


Solution

  • For anyone who needs it. I've taken @arconaut answer and added it to my code so foo looks like this now:

       class foo
       {
          int id;
          string name;
          public foo(int Id, string Name)
          {
             id = Id;
             name = Name;
          }
          public override bool Equals(object obj)
          {
             return Equals(obj as foo);
          }
    
          public bool Equals(foo obj)
          {
             if (obj == null) return false;
             return (id == obj.id && name == obj.name);
          }
    
          public override int GetHashCode()
          {
             var hashCode = 352033288;
             hashCode = hashCode * -1521134295 + id.GetHashCode();
             hashCode = hashCode * -1521134295 + name.GetHashCode();
             return hashCode;
          }
       }
    

    Im still not sure about the hashcode but it works. so thx