Create a list from two object lists with linq


I have the following situation

class Person
    string Name;
    int Value;
    int Change;

List<Person> list1;
List<Person> list2;

I need to combine the 2 lists into a new List<Person> in case it's the same person the combine record would have that name, value of the person in list2, change would be the value of list2 - the value of list1. Change is 0 if no duplicate

4/7/2017 3:29:04 PM

This can easily be done by using the Linq extension method Union. For example:

var mergedList = list1.Union(list2).ToList();

This will return a List in which the two lists are merged and doubles are removed. If you don't specify a comparer in the Union extension method like in my example, it will use the default Equals and GetHashCode methods in your Person class. If you for example want to compare persons by comparing their Name property, you must override these methods to perform the comparison yourself. Check the following code sample to accomplish that. You must add this code to your Person class.

/// <summary>
/// Checks if the provided object is equal to the current Person
/// </summary>
/// <param name="obj">Object to compare to the current Person</param>
/// <returns>True if equal, false if not</returns>
public override bool Equals(object obj)
    // Try to cast the object to compare to to be a Person
    var person = obj as Person;

    return Equals(person);

/// <summary>
/// Returns an identifier for this instance
/// </summary>
public override int GetHashCode()
    return Name.GetHashCode();

/// <summary>
/// Checks if the provided Person is equal to the current Person
/// </summary>
/// <param name="personToCompareTo">Person to compare to the current person</param>
/// <returns>True if equal, false if not</returns>
public bool Equals(Person personToCompareTo)
    // Check if person is being compared to a non person. In that case always return false.
    if (personToCompareTo == null) return false;

    // If the person to compare to does not have a Name assigned yet, we can't define if it's the same. Return false.
    if (string.IsNullOrEmpty(personToCompareTo.Name) return false;

    // Check if both person objects contain the same Name. In that case they're assumed equal.
    return Name.Equals(personToCompareTo.Name);

If you don't want to set the default Equals method of your Person class to always use the Name to compare two objects, you can also write a comparer class which uses the IEqualityComparer interface. You can then provide this comparer as the second parameter in the Linq extension Union method. More information on how to write such a comparer method can be found on

1/9/2010 10:51:17 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow