LINQ Union does not go to overridden Equals method

I am trying to remove duplicates when merging two lists of objects (vehicles) using LINQ , for example:

 var list = list1.Union(list2); 

I have an overridden the Equal method and the code will not even go into it. However, this code takes a step in redefinition:

 Vehicle v1 = new Vehicle(); Vehicle v2 = new Vehicle(); if (v1.Equals(v2))....... 

EDIT

Signatures for redefining vehicles are given here:

I also implement IEquatable<Vehicle>

  public bool Equals(Vehicle other) { } public override int GetHashCode() { } 

I would prefer not to pass a comparison with the Union method, since I want thelogic in the Vehicle class.

What have I done wrong here?

+7
c # linq
source share
1 answer

You have nothing to do with IEquatable<Vehicle> , it's just an option, but not a must-do . I think that you did not redefine your Equals correctly, it should look like this:

  public override bool Equals(object other) { //your own code } public override int GetHashCode() { //your own code } 

NOTE the keyword overrides the argument of type object , which corresponds to the virtual Equals method of the base object.

+5
source share

All Articles