Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to form a union of two lists

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}

like image 270
R.S.K Avatar asked Nov 22 '12 03:11

R.S.K


People also ask

What is the union of two lists?

Union of two lists means combining two lists into one, all the elements from list A and list B, and putting them inside a single new list.

How do you find the union of a list?

To perform the union of two lists in python, we just have to create an output list that should contain elements from both the input lists. For instance, if we have list1=[1,2,3,4,5,6] and list2=[2,4,6,8,10,12] , the union of list1 and list2 will be [1,2,3,4,5,6,8,10,12] .


2 Answers

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

var aUb = A.Union(B).ToList(); 
like image 26
Sergey Kalinichenko Avatar answered Sep 20 '22 18:09

Sergey Kalinichenko


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 
like image 178
Tilak Avatar answered Sep 22 '22 18:09

Tilak