我有两个员工列表,我只想从中获取唯一记录,但这有一个转折点。每个列表都有一个 Employee 类:
public class Employee
{
// I want to completely ignore ID in the comparison
public int ID{ get; set; }
// I want to use FirstName and LastName in comparison
public string FirstName{ get; set; }
public string LastName{ get; set; }
}
我想比较匹配的唯一属性是名字和姓氏。我想在比较中完全忽略 ID。allFulltimeEmployees 列表中有 3 名员工,allParttimeEmployees 列表中有 3 名员工。名单中的两个项目的名字和姓氏匹配 - Sally Jones 和 Fred Jackson。列表中有一项不匹配,因为 FirstName 相同,但 LastName 不同:
emp.id = null; // not populated or used in comparison
emp.FirstName = "Joe"; // same
emp.LastName = "Smith"; // different
allFulltimeEmployees.Add(emp);
emp.id = 3; // not used in comparison
emp.FirstName = "Joe"; // a match
emp.LastName = "Williams"; // not a match - different last name
allParttimeEmployees.Add(emp);
所以我想在比较两个列表的过程中忽略类中的 ID 属性。我想将 Joe Williams 标记为不匹配,因为两个列表中的 Smith 和 Williams 的姓氏不匹配。
// finalResult should only have Joe Williams in it
var finalResult = allFulltimeEmployees.Except(allParttimeEmployees);
我尝试使用 IEqualityComparer 但它不起作用,因为它在参数中使用单个 Employee 类而不是 IEnumerable 列表:
public class EmployeeEqualityComparer : IEqualityComparer<Employee>
{
public bool Equals(Employee x, Employee y)
{
if (x.FirstName == y.FirstName && x.LastName == y.LastName)
{
return true;
}
else
{
return false;
}
}
public int GetHashCode(Employee obj)
{
return obj.GetHashCode();
}
}
我怎样才能成功地做我想做的事并执行这个操作?谢谢你的帮助!