Simplest way to form a union of two lists

C#.NetLinqListUnion

C# Problem Overview


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}

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

var aUb = A.Union(B).ToList();

Solution 3 - C#

Using LINQ's Union

Enumerable.Union(ListA,ListB);

or

ListA.Union(ListB);

Solution 4 - C#

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);

Solution 5 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionR.S.KView Question on Stackoverflow
Solution 1 - C#TilakView Answer on Stackoverflow
Solution 2 - C#Sergey KalinichenkoView Answer on Stackoverflow
Solution 3 - C#Prabhu MurthyView Answer on Stackoverflow
Solution 4 - C#code4lifeView Answer on Stackoverflow
Solution 5 - C#Mikael EngverView Answer on Stackoverflow