0

I have two custom list objects with the properties: ID(AutoGenerated -Guid), EmpoyeeID, Firstname, lastname, and Employmentstatus.

I want to use the Except() keyword to compare the two lists for differences, but I want to specifically ignore the ID property.

How do I ignore the ID property to find the differences between the two lists?

Necoras
  • 6,743
  • 3
  • 24
  • 45
Rahul Sharma
  • 73
  • 3
  • 6
  • Create a class that inherits IComparer. See msdn : https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.icomparer-1?view=netframework-4.7.2 – jdweng Feb 14 '19 at 16:37
  • 2
    Possible duplicate of [Linq Except with custom IEqualityComparer](https://stackoverflow.com/questions/7042090/linq-except-with-custom-iequalitycomparer) – Gabriel Negut Feb 14 '19 at 16:37
  • 1
    Not an answer, but it seems strange to me that EmployeeId would change... Shouldn't that be the perfect property to compare for finding out if new records have been added? It seems a property like EmployeeId should generally not change through the life of the employee record – Jonathan Feb 14 '19 at 16:39

1 Answers1

3

You can create your own custom implementation of IEqualityComparer like the below:

Here is a Fiddle example where the last four employees from List1 should be returned: https://dotnetfiddle.net/f3sBLq

In this example, EmployeeComparer inherits from IEqualityComparer<Employee> where Employee is a class with the properties you listed (EmployeeID, Firstname, Lastname, Employmentstatus)

public class EmployeeComparer : IEqualityComparer<Employee>
{
    public int GetHashCode(Employee co)
    {
        if (co == null)
        {
            return 0;
        }

        //You can use any property you want (other than EmployeeID for your purposes); the GetHashCode metho is used to generate an address to where the object is stored
        return co.Employmentstatus.GetHashCode();
    }

    public bool Equals(Employee x1, Employee x2)
    {
        if (object.ReferenceEquals(x1, x2))
        {
            return true;
        }

        if (object.ReferenceEquals(x1, null) || object.ReferenceEquals(x2, null))
        {
            return false;
        }

        // Check for equality with all properties except for EmployeeID
        return x1.Employmentstatus == x2.Employmentstatus && x1.Firstname == x2.Firstname && x1.Lastname == x2.Lastname;
    }
}

Then you can use it like this:

var results = List2.Except(List1, new EmployeeComparer()).ToList();

Edit: Original question did not list ID as property and requested how to exclude EmployeeID which is what this answer and Fiddle link example are both based on.

Stemado
  • 599
  • 5
  • 10