与我班级的名单不同

时间:2014-05-06 05:43:34

标签: c# list

我有一个班级:

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

但没有任何反应。谁能告诉我什么错了?

2 个答案:

答案 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>

的Comparer实施

示例:

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

参考:Distinctly LINQ – Getting a Distinct List of Objects