90

What is the easiest way to compare the elements of two lists say A and B with one another, and add the elements which are present in B to A only if they are not present in A?

To illustrate, Take list A = {1,2,3} list B = {3,4,5}

So after the operation AUB I want list A = {1,2,3,4,5}

Tilak
  • 30,108
  • 19
  • 83
  • 131
R.S.K
  • 2,114
  • 4
  • 26
  • 32
  • If someone is looking for a more dynamic approach watch this: https://stackoverflow.com/questions/6948587/union-multiple-number-of-lists-in-c-sharp – UNeverNo Nov 20 '19 at 15:42
  • It should be noted that if you don't need some of the aspects specific to a List (such as maintaining order), [HashSet](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1?redirectedfrom=MSDN&view=net-7.0) exists to prevent duplicates. – fenix.shadow Dec 29 '22 at 18:36

5 Answers5

176

If it is a list, you can also use AddRange method.

var listB = new List<int>{3, 4, 5};  
var listA = new List<int>{1, 2, 3, 4, 5};

listA.AddRange(listB); // listA now has elements of listB also.

If you need new list (and exclude the duplicate), you can use Union

  var listB = new List<int>{3, 4, 5};  
  var listA = new List<int>{1, 2, 3, 4, 5};
  var listFinal = listA.Union(listB);

If you need new list (and include the duplicate), you can use Concat

  var listB = new List<int>{3, 4, 5};  
  var listA = new List<int>{1, 2, 3, 4, 5};
  var listFinal = listA.Concat(listB);

If you need common items, you can use Intersect.

var listB = new List<int>{3, 4, 5};  
var listA = new List<int>{1, 2, 3, 4};  
var listFinal = listA.Intersect(listB); //3,4
JumpingJezza
  • 5,498
  • 11
  • 67
  • 106
Tilak
  • 30,108
  • 19
  • 83
  • 131
  • 3
    Since this answer pops up first when searching for related operations, it would be nice to add [Intersect](https://msdn.microsoft.com/en-us/library/bb460136(v=vs.110).aspx) – Joel Bourbonnais Nov 14 '17 at 15:51
  • 1
    Thank you for your detailed explanation for all the related methods. Thank you very much. keep it up. – Shehan Silva Dec 24 '17 at 11:33
31

The easiest way is to use LINQ's Union method:

var aUb = A.Union(B).ToList();
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
10

Using LINQ's Union

Enumerable.Union(ListA,ListB);

or

ListA.Union(ListB);
Prabhu Murthy
  • 9,031
  • 5
  • 29
  • 36
5

I think this is all you really need to do:

var listB = new List<int>{3, 4, 5};
var listA = new List<int>{1, 2, 3, 4, 5};

var listMerged = listA.Union(listB);
code4life
  • 15,655
  • 7
  • 50
  • 82
0

If it is two IEnumerable lists you can't use AddRange, but you can use Concat.

IEnumerable<int> first = new List<int>{1,1,2,3,5};
IEnumerable<int> second = new List<int>{8,13,21,34,55};

var allItems = first.Concat(second);
// 1,1,2,3,5,8,13,21,34,55
Mikael Engver
  • 4,634
  • 4
  • 46
  • 53