C# linq groupby returns incorrect groups -
i trying understand how linq works. wrote test app , not working way expect to. following code, expecting see items "test1" , "test4" grouped together, not getting that. instead getting 4 separate groups. meaning 1 of items getting grouped together. can explain doing wrong? thanks.
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);
why tcgroup contain 4 groups? expecting 3 groups.
the error happens because override equals
without overriding gethashcode
. these 2 must overriden together, otherwise groupby
not work.
add code class fix issue:
public override int gethashcode() { // ignoring x3 equality, hash code must ignore return 31*x1+x2; }