Home > Backend Development > C++ > How to Merge Two Lists of Person Objects Using LINQ and Handle Attribute Updates Based on Name Matching?

How to Merge Two Lists of Person Objects Using LINQ and Handle Attribute Updates Based on Name Matching?

Susan Sarandon
Release: 2024-12-26 19:04:13
Original
496 people have browsed it

How to Merge Two Lists of Person Objects Using LINQ and Handle Attribute Updates Based on Name Matching?

Create a List from Two Object Lists with Linq

Consider the following scenario:

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

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

The objective is to combine the two lists into a new List. If the combined record pertains to the same person, its attributes should align as follows: the name should match, the value should reflect that of the person in list2, and the change should be the value in list2 minus the value in list1. Otherwise, the change should be 0.

Solution:

The Linq method Union is a perfect fit for this task:

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

This operation merges the two lists, removing duplicates. By default, it will invoke the Equals and GetHashCode methods defined within the Person class. However, if these methods are not overridden, they may not effectively compare our custom objects (e.g., using the Name property for comparison).

Overriding Equals and GetHashCode:

To ensure accurate comparisons by name, override the methods as follows:

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

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

public bool Equals(Person personToCompareTo)
{
    if (personToCompareTo == null || string.IsNullOrEmpty(personToCompareTo.Name))
        return false;

    return Name.Equals(personToCompareTo.Name);
}
Copy after login

Custom Comparer:

Alternatively, create a custom comparer that implements the IEqualityComparer interface. This comparer can be provided as the second argument to the Union method. More information on custom comparers can be found here: http://msdn.microsoft.com/en-us/library/system.collections.iequalitycomparer.aspx.

The above is the detailed content of How to Merge Two Lists of Person Objects Using LINQ and Handle Attribute Updates Based on Name Matching?. 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