[英]Add elements from one list to another C#
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. 列表A包含x项目列表B,其中包含y项目。
I want to add elements of B to A so that A now contains X+Y items. 我想将B的元素添加到A中,以便A现在包含X + Y项。 I know this can done using a loop but is there a built in method for this?
我知道这可以使用循环完成但是有一个内置的方法吗? Or any other technique?
还是其他任何技术?
Your question describes the List.AddRange method, 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 listB
were added to listA
in the AddRange
call. 示出的所有元素
listB
加入listA
在AddRange
呼叫。
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 listA
instead: 您可以使用后者来重新分配
listA
:
listA = listA.Concat(listB).ToList();
but there isn't any particular advantage to that over AddRange
if you're okay with modifying one of the original lists in the first place. 但是如果您可以首先修改其中一个原始列表,那么对
AddRange
没有任何特别的优势。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.