Home >Backend Development >C++ >How Can LINQ's Union Method Combine Two Lists of Objects and Handle Duplicates?
When dealing with multiple object lists, the need to combine them into a cohesive unit often arises. In this scenario, you have two lists of Person objects and wish to merge them, calculating the Change value as the difference between their respective values if duplicates exist.
To achieve this, LINQ provides a powerful extension method: Union. By default, this method removes duplicates based on the Equals and GetHashCode methods defined in the Person class. If your Person class doesn't have these methods overridden or you want to perform a custom comparison, here's how:
Within your Person class, override the Equals and GetHashCode methods to compare objects based on your desired property, such as Name:
public override bool Equals(object obj) { // Convert object to a Person for comparison var person = obj as Person; if (person == null) return false; return Equals(person); } public override int GetHashCode() { return Name.GetHashCode(); } public bool Equals(Person personToCompareTo) { if (personToCompareTo == null) return false; if (string.IsNullOrEmpty(personToCompareTo.Name)) return false; return Name.Equals(personToCompareTo.Name); }
Implement a comparer class that implements the IEqualityComparer interface. Provide this comparer as the second parameter in the Linq Union extension method:
// Implement IEqualityComparer<Person> public bool Equals(Person x, Person y) { // Your custom comparison here } public int GetHashCode(Person person) { // Your custom hash code generation here } var mergedList = list1.Union(list2, new MyPersonComparer());
The above is the detailed content of How Can LINQ's Union Method Combine Two Lists of Objects and Handle Duplicates?. For more information, please follow other related articles on the PHP Chinese website!