你的类是一样的,所以我相信你想要做的是比较MyObject类型的两个对象列表:
public class MyObject
{
public string Name { get; set; }
public string Value { set; get; }
public Guid ID { get; set; }
}
我发现最简单的方法是让MyObject 类实现IComparable 接口,而无需编写单独的IEqualityComparer。这在halfway down this page有详细解释,但这是你的类在实现接口后的样子:
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;
}
}
一旦您的类具有Equals() 和GetHashCode() 方法,LINQ 的Except() 方法将自动工作:
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 现在有橙子和柠檬,但没有苹果。我喜欢这个解决方案,因为最后一行的代码清晰易读。