4

我试图了解 linq 是如何工作的。我写了一个测试应用程序,但它没有按我期望的方式工作。从下面的代码中,我希望看到项目“test1”和“test4”组合在一起,但我不明白。相反,我要返回 4 个单独的组。意味着其中一项正在组合在一起。有人可以解释我做错了什么吗?谢谢。

public class linqtest
{   public int x1;
    public int x2;
    public string x3;

    public linqtest(int a, int b, string c)
    {
        x1 = a;
        x2 = b;
        x3 = c;

    }

    public bool Equals(linqtest other)
    {

        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;

        return x1 == other.x1 &&
                x2 == other.x2;

    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != typeof(linqtest)) return false;
        return Equals((linqtest)obj);
    }
}
linqtest tc14 = new linqtest(1, 4, "test1");
inqtest tc15 = new linqtest(3, 5, "test2");
linqtest tc16 = new linqtest(3, 6, "test3");
linqtest tc16a = new linqtest(1, 4, "test4");

List<linqtest> tclistitems = new List<linqtest>();
tclistitems.Add(tc14);
tclistitems.Add(tc15);
tclistitems.Add(tc16);
tclistitems.Add(tc16a);

IEnumerable<IGrouping<linqtest, linqtest>> tcgroup = tclistitems.GroupBy(c => c);

为什么 tcgroup 包含 4 个组?我期待3组。

4

2 回答 2

6

发生错误是因为您覆盖Equals而不覆盖GetHashCode. 这两个必须一起覆盖,否则GroupBy将不起作用。

将此代码添加到您的课程以解决此问题:

public override int GetHashCode()
{
    // You are ignoring x3 for equality, so hash code must ignore it too
    return 31*x1+x2;
}
于 2013-04-25T15:14:06.827 回答
2

您不需要覆盖Equal方法,只需利用匿名类,因为匿名类基于以下属性进行比较struct

tcgroup = tclistitems.GroupBy(c => new { c.x1, c.x2 });
于 2013-04-25T15:17:11.823 回答