-1

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?

Indycate
  • 11
  • 3
  • 3
    You're not overriding `Equals` or `GetHashCode`. If you override those to indicate when you consider to distinct objects to be equal, the code will work with no other change. Or you could create an `IEqualityComparer` and pass that to the `Intersect` method as a second argument. (As an aside, it's best to make sample code follow regular .NET naming conventions, where class names are PascalCased and parameter names are camelCased.) – Jon Skeet Nov 18 '20 at 08:39
  • If they're not the same _instance_, what defines that they are the _same_? Is it the `id`? – Martin Nov 18 '20 at 08:46
  • @Martin im not 100% sure if Id is sufficient enough but at least Id should be equal. – Indycate Nov 18 '20 at 08:56

2 Answers2

2

You can override how .NET "decides" if the objects are equal - by overriding Equals and GetHashCode.

Visual Studio can help with that: https://learn.microsoft.com/en-us/visualstudio/ide/reference/generate-equals-gethashcode-methods?view=vs-2019

arconaut
  • 3,227
  • 2
  • 27
  • 36
  • i managed to override the Equals methode but I'm not sure on how to override GetHashCode() – Indycate Nov 18 '20 at 08:53
  • Does the article I linked to in the answer help? Visual Studio can automatically generate it. Also, you can take a look at more examples here: https://learn.microsoft.com/en-us/dotnet/api/system.object.gethashcode?view=net-5.0 – arconaut Nov 18 '20 at 09:09
0

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

Indycate
  • 11
  • 3