日期:2014-05-20 浏览次数:21111 次
void Main()
{
List<Employee> emplist1 = new List<Employee>() { new Employee() { Id = 1, Name = "Scott" }, new Employee() { Id = 2, Name = "Lilly" }, new Employee() { Id = 3, Name = "Peter" } };
List<Employee> emplist2 = new List<Employee>() { new Employee() { Id = 1, Name = "Scott" }, new Employee() { Id = 4, Name = "Kate" } };
foreach (var r in emplist1.Except(emplist2,new EmployeeComparer()))
{
Console.WriteLine("{0},{1}", r.Id, r.Name);
}
/*
2,Lilly
3,Peter
*/
}
class Employee
{
private int id;
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public int Id
{
get { return id; }
set { id = value; }
}
}
class EmployeeComparer : IEqualityComparer<Employee>
{
// Products are equal if their names and product numbers are equal.
public bool Equals(Employee x, Employee y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.Id == y.Id && x.Name == y.Name;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(Employee ep)
{
//Check whether the object is null
if (Object.ReferenceEquals(ep, null)) return 0;
//Get hash code for the Name field if it is not null.
int hashEmployeeName = ep.Name == null ? 0 : ep.Name.GetHashCode();
//Get hash code for the Code field.
int hashEmployeeId = ep.Id.GetHashCode();
//Calculate the hash code for the product.
return hashEmployeeName ^ hashEmployeeId;
}
}
------解决方案--------------------
http://msdn.microsoft.com/en-us/library/bb336390.aspx