The Except
-method has an overload, which takes an IEqualityComparer<T>
as the last argument.
There is a sample in the MSDN: https://msdn.microsoft.com/en-us/library/bb336390.aspx
EDIT
It is possible to create an list of anonymous objects and compare them with a special IEqualityComparer<T>
. Here is the comparer class:
class MyEqualityComparer : IEqualityComparer<object>
{
#region IEqualityComparer<object> Members
bool IEqualityComparer<object>.Equals(object x, object y)
{
return (x as dynamic).Id == (y as dynamic).Id;
}
int IEqualityComparer<object>.GetHashCode(object obj)
{
return ((obj as dynamic).Id as object).GetHashCode();
}
#endregion
}
And the LINQ Expression should look like this:
var result = lst1.Select(x => new { Id = x.Id, Obj = x })
.Except(lst2.Select(x => new { Id = x.Id, Obj = x }),
new MyEqualityComparer())
.Select(x => (x as dynamic).Obj as Type1);
I know, it is a bad style to use dynamic in this case, you can change it without any problem to a real type.