I am trying to understand how linq works. i wrote a test app and it is not working the way i expect it to. from the following code, i am expecting to see items "test1" and "test4" grouped together, but i am not getting that. instead I am getting back 4 separate groups. meaning one of the items are getting grouped together. can someone explain what i am 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 does tcgroup contain 4 groups? i was expecting 3 groups.
The error happens because you override Equals
without overriding GetHashCode
. These two must be overriden together, otherwise GroupBy
will not work.
Add this code to your class to fix the issue:
public override int GetHashCode()
{
// You are ignoring x3 for equality, so hash code must ignore it too
return 31*x1+x2;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With