How to merge two lists and remove duplicates

23,413

Solution 1

Try the Union extension method.

var result = listA.Union(listB).ToList();

Union produces the set union of two sequences by using the default equality comparer so the result contains only distinct values from both lists.

Solution 2

Use Concat() and then Distinct() Linq methods

listA.Concat(listB).Distinct().ToList();
Share:
23,413
LuisOsv
Author by

LuisOsv

QA Automation Engineer

Updated on July 21, 2022

Comments

  • LuisOsv
    LuisOsv almost 2 years

    Given I have two list like the following:

    var listA = new List<string> { "test1", "test2", "test3" };
    var listB = new List<string> { "test2", "test3", "test4" };
    

    I want a third list with:

    var listC = new List<string> { "test1", "test2", "test3", "test4"}
    

    Is there a way to get this?