Merge Lists and Removing duplicates C#

We have 2 Lists and we want to make it one and also remove the repeating values, i.e., we want a Union of the two Lists but no repeating value.

We can always do it by iterating the 2nd List, and adding all elements to the first list if it does not contain already.

Orr iterating both Lists and populating another List with unique elements in both lists, but that would be a very naive approach as it is not an efficient solution.


A better approach is if we can find something that comes with .NET Framework.

 

List.Union is an extension method, which takes two arguments,


 – the List

– the Comparer to compare the values in the list, If this comparer is null, Default Equality comparer will be used.
     You need to implement your own Comparer if you need custom criteria to define a duplicate.

Here is the example:

List<int> one = new List<int> { 1, 2, 3, 4, 5 };

List<int> one = new List<int> { 1, 2, 3, 4, 5 };

// if 2nd parameter is null, Default equality Comparer will be used.
var result = one.Union(second, new MyEqualComparer());
//A new list will be returned, without duplicate.

// My custom Equality Comparer,
public class MyEqualComparer : IEqualityComparer<int>
{
    public bool Equals( int x, int y )
    {
        return x == y;
    }
}

 

I have used an Equality comparer in the example, you may be using your custom Comparer.
You can find more on how to use IComparable and IComparer here.