Say I have an object Person with the properties below:
public class Person
{
public int ID { get; set; }
public int EmployeeNo { get; set; }
public string JobDescription { get; set; }
public string Code { get; set; }
}
How would I dynamically check the equality of specific properties by name?
eg.
var dynamicEqualityComparer = RetrieveDynamicEqualityComparer("ID", "JobDescription");
var intersectedPersons = listOfPerson1.Intersect(listOfPerson2, dynamicEqualityComparer);
The above snippit would use the default linq intersect method using the dynamically generated equality comparison method which only compares the fields "ID" and "JobDescription".
I would assume that something like this would have been easy to find, but so far have not been able to locate anything of the sort.
The solution I came to is below:
The equality comparer class looks like:
To create this class, you pass in a list of strings representing the objects property names.
To call this class, I used the following bit of code:
This creates a custom equality comparer for any class with the properties "EmployeeNo" and "ID".
I used this comparer when checking if two tables contain the same entries where equality doesn't necessarily mean that every single field is equal..
Put this in your person class then with your instance you can call equals
since the override of tostring accounts for all state data,in override equals you simply leverage your own implementation of ToString().
this is the implementation of the IComparer<> interface of type Person