GroupBy具有具体的类密钥

时间:2017-07-20 07:50:56

标签: c# .net

我尝试使用GroupBy不是匿名类型,而是使用具体类作为键。我压倒了Equals方法。它没有帮助。我看到了使用混凝土类型作为关键的问题,但没有说使用它的任何麻烦。 调试会话结果位于附加图像picture

class Program
{
    static void Main(string[] args)
    {
        DateTime val = DateTime.Now;
        bool testEquality = new Class2(val) == new Class2(val);
        bool testEquality2 = new Class2(val).Equals(new Class2(val));
        bool testEquality3 = new Class2(val).Equals(new Class2(val.AddDays(1)));
        List<Class1> list = new List<Class1>
        {
            new Class1(1, val),
            new Class1(2, val.AddHours(1)),
            new Class1(2, val.AddHours(2)),
            new Class1(2, val.AddHours(1)),
            new Class1(2, val.AddHours(1)),
        };
        var grouped = list.GroupBy(x => new Class2(x.prop2));

    }
}
internal class Class1
{
    public int prop1;
    public DateTime prop2;
    public Class1(int v1, DateTime v2)
    {
        prop1 = v1;
        prop2 = v2;
    }
}
internal class Class2
{
    public DateTime prop2;
    public Class2(DateTime v)
    {
        prop2 = v;
    }
    public override bool Equals(object obj)
    {
        return this.prop2 == ((Class2)obj).prop2;
    }
}

2 个答案:

答案 0 :(得分:1)

您还需要在Class2中覆盖GetHashCode。

internal class Class2
{
    public DateTime prop2;
    public Class2(DateTime v)
    {
        prop2 = v;
    }
    public override bool Equals(object obj)
    {
        return this.prop2 == ((Class2)obj).prop2;
    }

    public override int GetHashCode()
    {
        return this.prop2.GetHashCode();
    }
}

Debugger

覆盖Equals时的最佳做法:

Why is it important to override GetHashCode when Equals method is overridden?

答案 1 :(得分:1)

您需要实施==!=运算符,所有Equals方法 GetHashCode才能获得“正确”的相等性检查在C#中。以下是一个例子。

public class Class2
{
    public DateTime prop2;
    public Class2(DateTime v)
    {
        prop2 = v;
    }

    public static bool operator ==(Class2 a, Class2 b)
    {
        if (ReferenceEquals(a, b))
        {
            return true;
        }

        return (object)a != null && a.Equals(b);
    }

    public static bool operator !=(Class2 a, Class2 b)
    {
        return !(a == b);
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as Class2);
    }

    protected bool Equals(Class2 other)
    {
        return other != null && prop2.Equals(other.prop2);
    }

    public override int GetHashCode()
    {
        return prop2.GetHashCode();
    }
}