形成两个列表联合的最简单方法

什么是最简单的方法来比较两个列表的元素说,A 和 B 相互之间,并添加的元素,目前在 B 到 A,只有当他们不存在于 A?

举个例子, 以列表 A = {1,2,3}为例 列表 B = {3,4,5}

所以行动结束后 列表 A = {1,2,3,4,5}

132487 次浏览

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

Using LINQ's Union

Enumerable.Union(ListA,ListB);

or

ListA.Union(ListB);

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

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