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;
We want to create a new List
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();
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(); }
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();
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!