Home > Backend Development > C++ > How Can I Combine Two Lists of Person Objects in C# Using LINQ, Handling Duplicates and Calculating Differences?

How Can I Combine Two Lists of Person Objects in C# Using LINQ, Handling Duplicates and Calculating Differences?

Susan Sarandon
Release: 2024-12-29 07:28:09
Original
610 people have browsed it

How Can I Combine Two Lists of Person Objects in C# Using LINQ, Handling Duplicates and Calculating Differences?

Creating a Combined List with Transformed Values Using LINQ

In the scenario presented, you have two lists of Person objects and require a new list that combines these lists. For identical Person objects, the merged entry should retain their shared name, possess the value from list2, and their change should be calculated as (list2.Value - list1.Value). If no duplication exists, the change should remain at zero.

To achieve this, utilize the LINQ Union extension method. For instance:

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

This action merges the two lists, eliminating duplicates. By default, the Equals and GetHashCode methods defined in your Person class are used to determine object equality. For customized comparison based on a property like Name, override these methods as follows:

public override bool Equals(object obj)
{
    // Check if obj is convertible to Person
    var person = obj as Person;
    return Equals(person);
}

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

public bool Equals(Person personToCompareTo)
{
    // Check for null or empty Name
    if (personToCompareTo == null || string.IsNullOrEmpty(personToCompareTo.Name)) return false;
    // Compare Names for equality
    return Name.Equals(personToCompareTo.Name);
}
Copy after login

Alternatively, define a comparer class implementing the IEqualityComparer interface and provide it as the second argument to the Union method for custom object comparison. For more details, refer to https://msdn.microsoft.com/en-us/library/system.collections.iequalitycomparer.aspx.

The above is the detailed content of How Can I Combine Two Lists of Person Objects in C# Using LINQ, Handling Duplicates and Calculating Differences?. 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