9

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?

CDspace
  • 2,639
  • 18
  • 30
  • 36
LuisOsv
  • 339
  • 1
  • 4
  • 13
  • 4
    have you googled it? there are too many result about it – esiprogrammer Jan 20 '17 at 15:23
  • 2
    Possible duplicate of [Simplest way to form a union of two lists](http://stackoverflow.com/questions/13505672/simplest-way-to-form-a-union-of-two-lists) – dana Jan 20 '17 at 15:24

3 Answers3

28

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.

Damian
  • 2,752
  • 1
  • 29
  • 28
2
listA.AddRange(listB).Distinct().ToList();
2

Use Concat() and then Distinct() Linq methods

listA.Concat(listB).Distinct().ToList();
nobody
  • 10,892
  • 8
  • 45
  • 63