C # linq groupby returns invalid groups

I am trying to understand how linq works. I wrote a test application, and it does not work as I expect. from the following code, I expect the elements "test1" and "test4" are grouped together, but I do not understand this. instead, I return 4 separate groups. which means that one of the elements is 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.

+4
source share
2 answers

The error occurs because you override Equals without overriding GetHashCode . These two must be combined with each other, otherwise GroupBy will not work.

Add this code to your class to fix the problem:

 public override int GetHashCode() { // You are ignoring x3 for equality, so hash code must ignore it too return 31*x1+x2; } 
+6
source

You do not need to override the Equal method, just use an anonymous class, as the anonymous class is compared based on properties such as struct :

 tcgroup = tclistitems.GroupBy(c => new { c.x1, c.x2 }); 
+2
source

All Articles