将 Distinct 与自定义对象列表一起使用
如何使 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
}
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要重写
Equals
和GetHashCode
。GetHashCode
应为所有被视为相等的实例返回相同的值。例如:
由于.Net的Uri类重写了GetHashCode,因此您可以简单地返回URL的哈希码。
You need to override
Equals
andGetHashCode
.GetHashCode
should return the same value for all instances that are considered equal.For example:
Since .Net's Uri class overrides GetHashCode, you can simply return the URL's hashcode.
您可以获取 aku 的比较器 的副本(注意
GetHashCode
实现但是),然后写这样的东西You could grab a copy of aku's comparer (beware of the
GetHashCode
implementation however), and then write something like this