Pregunta

¿Cómo puedo hacer el Distinct() El método funciona con una lista de objetos personalizados (Href En este caso), así es como se ve el objeto actual:

public class Href : IComparable, IComparer<Href>
{
    public Uri URL { get; set; }
    public UrlType URLType { get; set; }

    public Href(Uri url, UrlType urltype)
    {
        URL = url;
        URLType = urltype;
    }


    #region IComparable Members

    public int CompareTo(object obj)
    {
        if (obj is Href)
        {
            return URL.ToString().CompareTo((obj as Href).URL.ToString());
        }
        else
            throw new ArgumentException("Wrong data type.");
    }

    #endregion

    #region IComparer<Href> Members

    int IComparer<Href>.Compare(Href x, Href y)
    {
        return string.Compare(x.URL.ToString(), y.URL.ToString());
    }

    #endregion
}
¿Fue útil?

Solución

Necesitas anular Equals y GetHashCode.

GetHashCode debe devolver el mismo valor para todas las instancias que se consideran iguales.

Por ejemplo:

public override bool Equals(object obj) { 
    Href other = obj as Href;
    return other != null && URL.Equals(other.URL);
} 

public override int GetHashCode() { 
    return URL.GetHashCode();
} 

Dado que la clase URI de .NET anula GethashCode, simplemente puede devolver el HASHCODE de la URL.

Otros consejos

Podrías tomar una copia de Comparador de Aku (Cuidado con el GetHashCode Sin embargo, la implementación), y luego escriba algo como esto

hrefList.Distinct(new Comparer<Href>((h1,h2)=>h1.URL==h2.URL))
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top