I have got two collections of same object
public class MyClass
{
public int Id {get;set;}
public string Name {get;set;}
public int Age{get;set;}
public string SSN{get;set;}
}
I have got two Collections (colA and colB) based on MyClass and want to compare them in a way to find New, Changed or Deleted Records. My starting point was
var diff = colA.Except(colB);
But this gives me wrong results and actually returning whole of colA
Then I made following changes in MyClass
public Class MyClass
{
// Properties
public int Id {get;set;}
public string Name {get;set;}
public int Age{get;set;}
public string SSN{get;set;}
// Added override versions of following
public override int GetHashCode()
{
unchecked
{
return
this.Id.GetHashCode();
}
}
public override bool Equals(object obj)
{
var data = obj as MyClass;
if ( (this.Id??0).Equals(data.Id ?? 0)
&& (this.Age??0).Equals(data.Age ?? 0)
&& (this.Name??string.Empty).Equals(data.Name ?? string.Empty)
&& (this.SSN??string.Empty).Equals(data.SSN ?? string.Empty)
)
return true;
return false;
}
}
To avoid failure on NULL I have applied NULL coalescing through ?? on different fields.
My Question is, Is this the best way of doing this or there can be a better way? and also how can this be changed to get what's been changed on field level?