Domanda

Come posso fare il Distinct() Metodo Funziona con un elenco di oggetti personalizzati (Href In questo caso), ecco come appare l'oggetto attuale:

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
}
È stato utile?

Soluzione

Devi sovrascrivere Equals e GetHashCode.

GetHashCode dovrebbe restituire lo stesso valore per tutte le istanze considerate uguali.

Per esempio:

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();
} 

Poiché la classe URI di .NET prevalga Gethashcode, puoi semplicemente restituire l'hashcode dell'URL.

Altri suggerimenti

Potresti prendere una copia di Il confronto di Aku (Fai attenzione al GetHashCode implementazione comunque), e quindi scrivere qualcosa del genere

hrefList.Distinct(new Comparer<Href>((h1,h2)=>h1.URL==h2.URL))
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top