Search code examples
linqentitycompareiequalitycomparericomparer

IEqualityComparer for class with many properties neither unique value


How do implementation for IEqualityComparer for this class?

The ID property is not unique. Neither properties has unique values.

The entity has 7 properties.

[Serializable()]
public class ServidorSeleccionadoDto
{
    [XmlAttribute()]
    public int Id { get; set; }

    [XmlAttribute()]
    public string Nombre { get; set; }

    [XmlAttribute()]
    public string IP { get; set; }

    [XmlAttribute()]
    public string Entorno { get; set; }

    [XmlAttribute()] // [XmlIgnore()]
    public string Habilitado { get; set; }

    [XmlAttribute()]
    public string Tipo { get; set; }

    [XmlAttribute()]
    public int IdGrupo { get; set; }
}

Solution

  • It looks like your object has an ID field. If this is unique to each object then you would only need to compare on that property.

    public Boolean Equals(ServidorSeleccionadoDto obj)
    {
       return this.ID == obj.ID;
    }
    

    Note: This would only work if ID is unique.


    If the ID property is not unique you will need to compare all your objects properties.

    public Boolean Equals(ServidorSeleccionadoDto obj)
    {
        return this.ID == obj.ID && 
               this.Nombre.Equals(obj.Nombre) && 
               ... etc
    }