我有一个班级:
private class Part
{
public string Id { get; set; }
public string Class { get; set; }
public override bool Equals(object obj)
{
Part part = obj as Part;
return this.Id == part.Id;
}
}
此外,我有一个这个类的列表,所以我需要在此列表中使用distinct。多数民众赞成在做什么:
List<Part> parts = new List<Part>();
//adding items
parts = parts.Distinct().ToList();
但没有任何反应。谁能告诉我什么错了?
答案 0 :(得分:8)
覆盖Equals
时,您还必须覆盖GetHashCode
:
private class Part
{
public string Id { get; set; }
public string Class { get; set; }
// Whenever overiding Equals
// You have to override this method too
public override int GetHashCode() {
return String.IsNullOrEmpty(Id) ? 0 : Id.GetHashCode();
}
public override bool Equals(object obj)
{
Part part = obj as Part;
// if obj is not of Part you should return false
if (Object.ReferenceEquals(null, part))
return false;
return this.Id == part.Id;
}
}
错误行为的原因是Distinct
首次测试 GetHashCode
和 只有 Equals
。
答案 1 :(得分:0)
要对您的班级执行Distinct
操作,您需要提供IEqualityComparer<T>
示例:强>
public class SelectedItemComparer : IEqualityComparer<Part>
{
public new bool Equals(Part x, Part y)
{
return x.Id == y.Id;
}
public int GetHashCode(Part source)
{
string code = source.Id.ToString();
return code.GetHashCode();
}
}
<强>用法:强>
List<Part> parts = new List<Part>();
//adding items
parts = parts.Distinct(new SelectedItemComparer()).ToList();