voidMain() { var list1 = new List<User> { new User {Name = "AAA", Age = 20}, new User {Name = "BBB", Age = 20}, new User {Name = "CCC", Age = 20}, new User {Name = "DDD", Age = 20}, new User {Name = "EEE", Age = 20}, }; var list2 = new List<User> { new User {Name = "DDD", Age = 20}, new User {Name = "EEE", Age = 20}, new User {Name = "FFF", Age = 20}, };
var result = list1.Except(list2, new UserEqualityComparer()).ToList(); result.Dump(); }
// Define other methods and classes here classUserEqualityComparer : IEqualityComparer<User> { publicboolEquals(User x, User y) { return x.Name == y.Name && x.Age == y.Age; }
publicintGetHashCode(User obj) { var name = obj.Name == null ? 0 : obj.Name.GetHashCode(); var age = obj.Age.GetHashCode(); return name ^ age; } } classUser { publicstring Name { get; set; } publicint Age { get; set; } }