将一个列表中的元素添加到另一个 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13467034/
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
Add elements from one list to another C#
提问by R.S.K
What is the simplest way to add elements of one list to another?
将一个列表的元素添加到另一个列表的最简单方法是什么?
For example, I have two lists:
例如,我有两个列表:
List A which contains x items List B which contains y items.
包含 x 项的列表 A 包含 y 项的列表 B。
I want to add elements of B to A so that A now contains X+Y items. I know this can done using a loop but is there a built in method for this? Or any other technique?
我想将 B 的元素添加到 A 以便 A 现在包含 X+Y 项。我知道这可以使用循环来完成,但是有没有内置的方法呢?或者其他什么技术?
采纳答案by Adam Mihalcin
Your question describes the List.AddRangemethod, which copies all the elements of its argument into the list object on which it is called.
您的问题描述了List.AddRange方法,该方法将其参数的所有元素复制到调用它的列表对象中。
As an example, the snippet
例如,片段
List<int> listA = Enumerable.Range(0, 10).ToList();
List<int> listB = Enumerable.Range(11, 10).ToList();
Console.WriteLine("Old listA: [{0}]", string.Join(", ", listA));
Console.WriteLine("Old listB: [{0}]", string.Join(", ", listB));
listA.AddRange(listB);
Console.WriteLine("New listA: [{0}]", string.Join(", ", listA));
prints
印刷
Old listA: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Old listB: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
New listA: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
showing that all the elements of listBwere added to listAin the AddRangecall.
显示在调用listB中添加了 的所有元素。listAAddRange
回答by Adam Lear
To join two lists, you can do
要加入两个列表,你可以这样做
listA.AddRange(listB); // listA will contain x+y items
or
或者
// listC contains x+y items, listA and listB are unchanged.
var listC = listA.Concat(listB);
You could use the latter to reassign listAinstead:
您可以使用后者来重新分配listA:
listA = listA.Concat(listB).ToList();
but there isn't any particular advantage to that over AddRangeif you're okay with modifying one of the original lists in the first place.
但是AddRange如果您可以首先修改原始列表中的一个,则没有任何特别的优势。

