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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13505672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:47:30  来源:igfitidea点击:

Simplest way to form a union of two lists

c#.netlinqlistunion

提问by R.S.K

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?

比较两个列表的元素(例如 A 和 B)的最简单方法是什么,并且仅当 A 中不存在时才将 B 中存在的元素添加到 A 中?

To illustrate, Take list A = {1,2,3} list B = {3,4,5}

举例说明,取列表 A = {1,2,3} 列表 B = {3,4,5}

So after the operation AUB I want list A = {1,2,3,4,5}

所以在操作 AUB 之后我想要列表 A = {1,2,3,4,5}

采纳答案by Tilak

If it is a list, you can also use AddRangemethod.

如果是列表,也可以使用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 new list (and exclude the duplicate), you can use Union

如果您需要新列表(并排除重复项),您可以使用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

如果您需要新列表(并包含副本),您可以使用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.

如果您需要常见项目,您可以使用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

回答by dasblinkenlight

The easiest way is to use LINQ's Unionmethod:

最简单的方法是使用LINQ的Union方法:

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

回答by code4life

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

回答by Prabhu Murthy

Using LINQ's Union

使用 LINQ 的联合

Enumerable.Union(ListA,ListB);

or

或者

ListA.Union(ListB);

回答by Mikael Engver

If it is two IEnumerable lists you can't use AddRange, but you can use Concat.

如果是两个 IEnumerable 列表,则不能使用AddRange,但可以使用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