The easiest way to form a union of two lists

What is the easiest way to compare the elements of two lists talking A and B with each other and add the elements that 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 AUB operation, I want the list A = {1,2,3,4,5}

+47
list c # linq union
Nov 22
source share
4 answers

If this is a list, you can also use AddRange .

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 a new list (and exclude 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 a new list (and specify a 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 elements, you can use Intersect .

var listB = new list {3, 4, 5};
var listA = new List {1, 2, 3, 4};
var listFinal = listA.Intersect (listB); // 3.4

+71
Nov 22 '12 at 4:01
source share

The easiest way is to use the LINQ Union method:

 var aUb = A.Union(B).ToList(); 
+23
Nov 22
source share

Using LINQ Union

 Enumerable.Union(ListA,ListB); 

or

 ListA.Union(ListB); 
+6
Nov 22 '12 at 4:00
source share

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); 
+5
Nov 22
source share



All Articles