Home > Backend Development > C++ > How Can LINQ's Union Method Combine Two Lists of Objects and Handle Duplicates?

How Can LINQ's Union Method Combine Two Lists of Objects and Handle Duplicates?

Linda Hamilton
Release: 2025-01-04 16:42:40
Original
778 people have browsed it

How Can LINQ's Union Method Combine Two Lists of Objects and Handle Duplicates?

Combine Two Object Lists with LINQ

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:

Overriding Equals and GetHashCode

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);
}
Copy after login

Using a Comparer Class

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());
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template