Home > Backend Development > C++ > How Can I Merge Two Lists of Objects in C# Using LINQ, Handling Duplicates and Custom Comparisons?

How Can I Merge Two Lists of Objects in C# Using LINQ, Handling Duplicates and Custom Comparisons?

Patricia Arquette
Release: 2025-01-01 10:24:11
Original
1023 people have browsed it

How Can I Merge Two Lists of Objects in C# Using LINQ, Handling Duplicates and Custom Comparisons?

Merging Object Lists with Linq

Combining two lists into a new list with specific conditions can be achieved using LINQ extension methods. Let's consider the following scenario:

class Person
{
    string Name;
    int Value;
    int Change;
}

List<Person> list1;
List<Person> list2;
Copy after login

We want to create a new List that combines list1 and list2. For identical persons, the combined record should retain their name, use the value from list2, and calculate Change as the difference between values from both lists.

Using the Union Method

The Union method in LINQ provides an easy way to merge two lists and remove duplicates. For example:

var mergedList = list1.Union(list2).ToList();
Copy after login

This will create a new mergedList that combines both list1 and list2, and any duplicate items will be excluded.

Custom Comparison for Equals and GetHashCode

If the default comparison of objects based on Equals and GetHashCode doesn't meet our requirements, we need to override these methods in the Person class. For example, here's how to make the comparison case-insensitive for the Name property:

public override bool Equals(object obj)
{        
    var person = obj as Person;

    return Equals(person);
}

public override int GetHashCode()
{
    return Name.ToLower().GetHashCode();
}

public bool Equals(Person personToCompareTo)
{
    return Name.ToLower() == personToCompareTo.Name.ToLower();
}
Copy after login

Using a Custom Comparer

Alternatively, we can define a custom comparer class implementing the IEqualityComparer interface. Then, we can provide this comparer to the Union method as a second parameter:

var comparer = new PersonComparer();
var mergedList = list1.Union(list2, comparer).ToList();
Copy after login

For more information on custom comparers, refer to the MSDN documentation.

The above is the detailed content of How Can I Merge Two Lists of Objects in C# Using LINQ, Handling Duplicates and Custom Comparisons?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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