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;
The objective is to combine the two lists into a new List
Solution:
The Linq method Union is a perfect fit for this task:
var mergedList = list1.Union(list2).ToList();
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); }
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!