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}
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
The easiest way is to use LINQ's Union
method:
var aUb = A.Union(B).ToList();
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);
Source: Stackoverflow.com