![](/img/trans.png)
[英]C# Linq add elements from one list<custom> to another comparing them and changing values
[英]Add elements from one list to another C#
将一个列表的元素添加到另一个列表的最简单方法是什么?
例如,我有两个列表:
列表A包含x项目列表B,其中包含y项目。
我想将B的元素添加到A中,以便A现在包含X + Y项。 我知道这可以使用循环完成但是有一个内置的方法吗? 还是其他任何技术?
您的问题描述了List.AddRange方法,该方法将其参数的所有元素复制到调用它的列表对象中。
作为一个例子,该片段
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));
版画
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]
示出的所有元素listB
加入listA
在AddRange
呼叫。
要加入两个列表,您可以这样做
listA.AddRange(listB); // listA will contain x+y items
要么
// listC contains x+y items, listA and listB are unchanged.
var listC = listA.Concat(listB);
您可以使用后者来重新分配listA
:
listA = listA.Concat(listB).ToList();
但是如果您可以首先修改其中一个原始列表,那么对AddRange
没有任何特别的优势。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.