I would like to understand how the GetHashCode
method works on lists of objects for equality. Given this example:
var user1 = new User { Id = Guid.NewGuid().ToString(), Name = "Chris" };
var user2 = new User { Id = Guid.NewGuid().ToString(), Name = "Jeff" };
var userList1 = new List<User> { user1, user2 }.OrderBy(o => o.Id);
var userList2 = new List<User> { user1, user2 }.OrderBy(o => o.Id);
var usersList1Hash = userList1.GetHashCode();
var usersList2Hash = userList2.GetHashCode();
var userListsEqual = usersList1Hash == usersList2Hash; // false
var userList1Json = JsonConvert.SerializeObject(userList1);
var userList2Json = JsonConvert.SerializeObject(userList2);
var usersList1JsonHash = userList1Json.GetHashCode();
var usersList2JsonHash = userList2Json.GetHashCode();
var userListsJsonEqual = usersList1JsonHash == usersList2JsonHash; // true
Why are the lists of objects not equal when comparing the hash codes?
Why are the list of objects equal when serializing to JSON strings and comparing the hash codes?