Groupby is grouped by the hashcode of the item, so it is best to override the gethashcode () method of the item.
Namespace consoleapplication5 {class program {static void main (string [] ARGs) {var list = new list <user> (); For (INT I = 0; I <5; I ++) {var user = new user {id = I, name = I + "User Name"}; List. add (User);} var Other = new user {id = 2, name = "Test 2"}; List. add (other); var groups = List. groupby (u => U); // directly group var result = from G in groups select new keyvaluepair <string, user> (key: G. f IRST (). name, value: G. first (); // because the user overwrites gethashcode (), the temp result has only five items var temp = result. tolist () ;}} public class user: iequatable <user >{ public int ID {Get; set;} public string name {Get; set;} public bool equals (user other) {return other! = NULL & this. ID = Other. ID;} public override int gethashcode () {return this. Id. gethashcode ();}}}
If you do not want to override gethashcode (), you can specify attributes for grouping.
{Class program {static void main (string [] ARGs) {var list = new list <user> (); For (INT I = 0; I <5; I ++) {var user = new user {id = I, name = I + "User Name"}; List. add (User);} var Other = new user {id = 2, name = "Test 2"}; List. add (other); var groups = List. groupby (u => U. ID); var result = from G in groups select new keyvaluepair <string, user> (key: G. first (). name, value: G. first (); // The result is still five var temp = result. tolist () ;}} public class user: iequatable <user >{ public int ID {Get; set;} public string name {Get; Set ;}}}
Reference: http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overridden