How to merge 2 List<T> and removing duplicate values from it in C#
Have you had a look at Enumerable.Union
This method excludes duplicates from the return set. This is different behavior to the Concat method, which returns all the elements in the input sequences including duplicates.
List<int> list1 = new List<int> { 1, 12, 12, 5};
List<int> list2 = new List<int> { 12, 5, 7, 9, 1 };
List<int> ulist = list1.Union(list2).ToList();
// ulist output : 1, 12, 5, 7, 9
why not simply eg
var newList = list1.Union(list2)/*.Distinct()*//*.ToList()*/;
oh ... according to the documentation you can leave out the .Distinct()
This method excludes duplicates from the return set
Union has not good performance : this article describe about compare them with together
var dict = list2.ToDictionary(p => p.Number);
foreach (var person in list1)
{
dict[person.Number] = person;
}
var merged = dict.Values.ToList();
Lists and LINQ merge: 4820ms
Dictionary merge: 16ms
HashSet and IEqualityComparer: 20ms
LINQ Union and IEqualityComparer: 24ms