我想了解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);
Run Code Online (Sandbox Code Playgroud)
为什么tcgroup包含4组?我期待3组.
发生错误是因为您覆盖Equals而没有覆盖GetHashCode.这两个必须一起覆盖,否则GroupBy将无法工作.
将此代码添加到您的类以解决此问题:
public override int GetHashCode()
{
// You are ignoring x3 for equality, so hash code must ignore it too
return 31*x1+x2;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
267 次 |
| 最近记录: |