Your classes are the same, so I believe what you want to do is to compare two lists of Objects of type MyObject:
public class MyObject
{
public string Name { get; set; }
public string Value { set; get; }
public Guid ID { get; set; }
}
I find the easiest way to do this, without having to write a separate IEqualityComparer, is to have the MyObject class implement the IComparable interface. This is explained in detail halfway down this page, but this is what your class would look like after implementing the interface:
public class MyObject : IEquatable <MyObject >
{
public string Name { get; set; }
public string Value { set; get; }
public Guid ID { get; set; }
public bool Equals(MyObject other)
{
//Check whether the compared object is null.
if (Object.ReferenceEquals(other, null)) return false;
//Check whether the compared object references the same data.
if (Object.ReferenceEquals(this, other)) return true;
//Check whether the objects properties are equal.
return Name.Equals(other.Name) && Value.Equals(other.Value) && ID.Equals(other.ID);
}
public override int GetHashCode()
{
//Get hash code for the Name field if it is not null.
int hashName = Name == null ? 0 : Name.GetHashCode();
//Get hash code for the Value field.
int hashCode = Value == null ? 0 : Value .GetHashCode();
//Get hash code for the IDfield.
int hashID = ID.GetHashCode();
//Calculate the hash code for the entire object.
return hashName ^ hashCode ^ hashId;
}
}
Once your class has the Equals() and GetHashCode() methods, the LINQ Except() method will automatically work:
List<MyObject> objects1 = { new MyObject{ Name = "apple", Value= "fruit", ID= 9 },
new MyObject{ Name = "orange", Value= "fruit", ID= 4 },
new MyObject{ Name = "lemon", Value= "fruit", ID= 12 } };
List<MyObject> objects2 = { new MyObject { Name = "apple", Value= "fruit", ID= 9 } };
List<MyObject> comparison = objects1.Except(objects2);
comparison now has orange and lemon, but not apple. I like this solution because of how legible the code is in the last line.