简体   繁体   中英

Use of Distinct with list of custom objects

How can I make the Distinct() method work with a list of custom object ( Href in this case), here is what the current object looks like:

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
}

You need to override Equals and GetHashCode .

GetHashCode should return the same value for all instances that are considered equal.

For example:

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

Since .Net's Uri class overrides GetHashCode, you can simply return the URL's hashcode.

您可以获取aku比较器的副本(但要注意GetHashCode实现),然后写这样的东西

hrefList.Distinct(new Comparer<Href>((h1,h2)=>h1.URL==h2.URL))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM