使用distinct与自定义对象名单 [英] Use of Distinct with list of custom objects

查看:107
本文介绍了使用distinct与自定义对象名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能让鲜明的()法的自定义对象( HREF 在这种情况下,一个工作列表),这里是当前对象的样子:

 公共类HREF:IComparable的,IComparer的< HREF> 
{
公众开放的URL {搞定;组; }
公共UrlType URLType {搞定;组; }

公共HREF(URI链接,UrlType urltype)
{
URL =网址;
URLType = urltype;
}


#地区IComparable的会员

公众诠释的CompareTo(obj对象)
{
如果(obj是HREF )
{
返回URL.ToString()的CompareTo((物镜为HREF。).URL.ToString());
}
,否则
抛出新的ArgumentException(错误的数据类型。);
}

#endregion

#地区的IComparer< HREF>会员

INT的IComparer< HREF> .Compare(HREF X,HREF Y)
{
返回的String.Compare(x.URL.ToString(),y.URL.ToString ());
}

#endregion
}


解决方案

您需要重写等于的GetHashCode



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



例如:

 公共覆盖布尔等于(obj对象){
HREF =其他如OBJ HREF;
返回其他= NULL&放大器;!&安培; URL.Equals(other.URL);
}

公共覆盖INT的GetHashCode(){
返回URL.GetHashCode();
}



由于NET的Uri类重写GetHashCode的,你可以简单地返回该URL的哈希码。


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.

这篇关于使用distinct与自定义对象名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆