Equals和GetHashCode

Equals每个实现都必须遵循以下约定:

* 自反性(Reflexive): x.equals(x)必须返回true.
* 对称性(Symmetric): x.equals(y)为true时,y.equals(x)也为true.
* 传递性(Transitive):

* 一致性(Consistence):

* 非null(Non-null): 如果x不是null,y为null,则x.equals(y)必须为false
GetHashCode:

* 两个相等对象根据equals方法比较时相等，那么这两个对象中任意一个对象的hashcode方法都必须产生同样的整数。
* 在我们未对对象进行修改时,多次调用hashcode使用返回同一个整数.在同一个应用程序中多次执行,每次执行返回的整数可以不一致.
*

IEqualityComparer实现

public class Student { public string Name { get; set; } public int Age { get;
set; } }

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

* 如果实例是引用类型，则只有引用相同时， Equals才会返回true。
* 如果实例是值类型，则仅当类型和值相同时， Equals才会返回true。
Distinct(IEnumerable, IEqualityComparer)

*
TSource source 的元素类型。

* source IEnumerable 要从中移除重复元素的序列。
*
comparer IEqualityComparer 用于比较值的 IEqualityComparer。

* IEnumerable

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; } }

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

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