'Dynamic equality in C#

Let's say that I have the following class:

public class TsvDataModel : IEquatable<TsvDataModel>
{
    public int ElementId { get; set; }

    public string Location { get; set; }
    public string RoomKey { get; set; 

    public decimal Area { get; set; }

    public bool Equals(TsvDataModel other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return ElementUid == other.ElementUid && Location == other.Location && RoomKey == other.RoomKey &&
               SubType == other.SubType;
    }

    // current equality comparison implementation
    public override bool Equals(object obj) => ReferenceEquals(this, obj) || (obj is TsvDataModel other && Equals(other));

    public override int GetHashCode() => HashCode.Combine(ElementUid, Location, RoomKey, SubType);
}

What I want is to create dynamic equality based on user-provided properties i.e. sometimes I want to compare only by ElementIds and sometimes to include/exclude other properties. I don't want to create all possible combinations. I tried using reflection to get properties via dynamic type and I can get value and type, but comparison is not working.

I'd prefer to pass in the properties as a list of property names (strings.)

I would like to use either IEqualityComparer or IEquitable (I'm using this object as HashSet<T>).



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source