Equals和GetHashCode
Equals每一個實現都必須遵循如下約定:ide
GetHashCode:性能
IEqualityComparer實現
下面咱們建立一個學生類,從而進一步的實現咱們對象數據的對比flex
public class Student { public string Name { get; set; } public int Age { get; set; } }
經過以下代碼咱們將經過distinct方法實現咱們的過濾.code
class Program { static void Main(string[] args) { List<Student> students = new List<Student> { new Student{ Name = "MR.A", Age = 32}, new Student{ Name = "MR.B", Age = 34}, new Student{ Name = "MR.A", Age = 32} }; Console.WriteLine("distinctStudents has Count = {0}", students.Distinct().Count());//distinctStudents has Count = 3 Console.ReadLine(); } }
咱們須要達到的是忽略相同數據的對象,可是並無達到咱們如期的效果.由於是distinct默認比較的是對象的引用...因此這樣達不到咱們預期效果.那咱們修改一下來實現咱們預期效果.對象
在默認狀況下Equals具備如下行爲:get
Distinct
經過使用指定的 IEqualityComparer
TSource source 的元素類型。it
comparer IEqualityComparer
咱們來看以下代碼片斷
public class StudentComparator : EqualityComparer<Student> { public override bool Equals(Student x,Student y) { return x.Name == y.Name && x.Age == y.Age; } public override int GetHashCode(Student obj) { return obj.Name.GetHashCode() * obj.Age; } }
上述代碼片斷若是兩個Equals返回的true而且GetHashCode返回相同的哈希碼,則認爲兩個對象相等.
重寫Equals和GetHashCode
var stu1 = new Student { Name = "MR.A", Age = 32 }; var stu2 = new Student { Name = "MR.A", Age = 32 }; bool result = stu1.Equals(stu2); //false because it's reference Equals
上述代碼片斷執行後結果非預期效果.咱們將進一步的去實現代碼,以達到預期效果....
public class Student { public string Name { get; set; } public int Age { get; set; } public override bool Equals(object obj) { var stu = obj as Student; if (stu == null) return false; return Name == stu.Name && Age == stu.Age; } public override int GetHashCode() { return Name.GetHashCode() * Age; } } var stu1 = new Student { Name = "MR.A", Age = 32 }; var stu2 = new Student { Name = "MR.A", Age = 32 }; bool result = stu1.Equals(stu2); //result is true
咱們再使用LINQ Distinct方法進行過濾和查詢,同時將會檢查Equals和GetHashCode
List<Student> students = new List<Student> { new Student{ Name = "MR.A", Age = 32}, new Student{ Name = "MR.B", Age = 34}, new Student{ Name = "MR.A", Age = 32} }; Console.WriteLine("distinctStudents has Count = {0}", students.Distinct().Count()); //distinctStudents has Count = 2