Pie*_* SS 9 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
}
Run Code Online (Sandbox Code Playgroud)
SLa*_*aks 16
你需要覆盖Equals和GetHashCode.
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();
}
Run Code Online (Sandbox Code Playgroud)
由于.Net的Uri类重写了GetHashCode,因此您只需返回URL的哈希码即可.
| 归档时间: |
|
| 查看次数: |
10450 次 |
| 最近记录: |