public sealed class MyObject1 { public string Name { get; set; } public string Value { set; get; } public Guid ID { get; set; } } public sealed class MyObject2 { public string Name { get; set; } public string Value { set; get; } public Guid ID { get; set; } }
public class myComparer: IEqualityComparer { public new bool Equals(object x, object y) { if (x is string ) return x == y; else if (x is Guid ) // maybe you want them to be equal if last char is equal. so you can do it here. return x == y; else return EqualityComparer
现在
List lst1 = new MyObject1 (); //add items here... List lst2 = new MyObject1 (); //add items here...
你可以将两种方式等同起来:
IStructuralEquatable equ = lst1 ; Console.WriteLine(equ.Equals(lst2 , EqualityComparer.Default)); or Console.WriteLine(equ.Equals(lst2 , new myComparer()));
public class MyObject : IEquatable { 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; } }
List 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 objects2 = { new MyObject { Name = "apple", Value= "fruit", ID= 9 } }; List comparison = objects1.Except(objects2);