Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Union not going into overridden Equals method

Tags:

c#

linq

I'm trying to remove duplicates when merging two lists of objects (vehicles) using LINQ like:

var list = list1.Union(list2);

I have overridden the Equals method and the code wont even step into it. However, this code does step into the override:

Vehicle v1 = new Vehicle();
Vehicle v2 = new Vehicle();

if (v1.Equals(v2)).......

EDIT

The signatures for the Vehicle overrides are here:

I also implement IEquatable<Vehicle>

 public bool Equals(Vehicle other)
 {                     
 }

 public override int GetHashCode()
 {            
 }

I would rather not pass a comparer to the Union method as I want thelogic in the Vehicle class.

What have I done wrong here?

like image 660
davy Avatar asked Oct 03 '13 10:10

davy


1 Answers

You have nothing to do with IEquatable<Vehicle>, it's just an option but not a required must-do. I think you didn't override 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 override and the argument of type object which matches the virtual Equals method of base object.

like image 132
King King Avatar answered Nov 08 '22 02:11

King King