简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM