I have two lists of employees from which I want to get only unique records, but it has a twist. Each list has an Employee class:
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; } }
The only properties that I want to compare to match are FirstName and LastName. I want to completely ignore the ID in comparison. There are 3 employees on the allFulltimeEmployees list, and 3 employees on the allParttimeEmployees list. The first name and surname coincide on two points in the lists - Sally Jones and Fred Jackson. There is one element in the list that does not match, because FirstName is the same, but LastName is different:
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);
Therefore, I want to ignore the ID property in the class when comparing two lists. I want to mark Joe Williams as a mismatch, since the last names of Smith and Williams in the two lists do not match.
I tried to use IEqualityComparer, but it does not work, since it uses only one Employee class in the parameters, and not in the IEnumerable list:
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(); } }
How can I successfully complete what I want and complete this operation? Thanks for any help!
source share