使用Distinct与自定义对象列表

时间:2010-06-09 14:23:19

标签: c# linq list distinct-values

如何使Distinct()方法使用自定义对象列表(在本例中为Href),这是当前对象的样子:

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
}

2 个答案:

答案 0 :(得分:16)

您需要覆盖EqualsGetHashCode

GetHashCode应为所有被认为相等的实例返回相同的值。

例如:

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

由于.Net的Uri类重写了GetHashCode,因此您只需返回URL的哈希码。

答案 1 :(得分:0)

你可以获取aku's comparer的副本(但要注意GetHashCode实现),然后写下这样的内容

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