【发布时间】:2010-10-06 08:49:29
【问题描述】:
如何将一个 Arraylist 数据移动到另一个 Arraylist。我尝试了很多选项,但输出的形式是数组而不是数组列表
【问题讨论】:
-
您想要元素的深拷贝还是浅拷贝?
如何将一个 Arraylist 数据移动到另一个 Arraylist。我尝试了很多选项,但输出的形式是数组而不是数组列表
【问题讨论】:
我找到了向上移动数据的答案,例如:
Firstarray.AddRange(SecondArrary);
【讨论】:
http://msdn.microsoft.com/en-us/library/system.collections.arraylist.addrange.aspx
从上面的链接中无耻的复制/粘贴
// Creates and initializes a new ArrayList.
ArrayList myAL = new ArrayList();
myAL.Add( "The" );
myAL.Add( "quick" );
myAL.Add( "brown" );
myAL.Add( "fox" );
// Creates and initializes a new Queue.
Queue myQueue = new Queue();
myQueue.Enqueue( "jumped" );
myQueue.Enqueue( "over" );
myQueue.Enqueue( "the" );
myQueue.Enqueue( "lazy" );
myQueue.Enqueue( "dog" );
// Displays the ArrayList and the Queue.
Console.WriteLine( "The ArrayList initially contains the following:" );
PrintValues( myAL, '\t' );
Console.WriteLine( "The Queue initially contains the following:" );
PrintValues( myQueue, '\t' );
// Copies the Queue elements to the end of the ArrayList.
myAL.AddRange( myQueue );
// Displays the ArrayList.
Console.WriteLine( "The ArrayList now contains the following:" );
PrintValues( myAL, '\t' );
除此之外,我认为Marc Gravell 是正确的;)
【讨论】:
首先 - 除非您使用 .NET 1.1,否则您应该避免使用 ArrayList - 更喜欢类型化集合,例如 List<T>。
当您说“复制”时 - 您要替换、追加还是新建?
对于追加(使用List<T>):
List<int> foo = new List<int> { 1, 2, 3, 4, 5 };
List<int> bar = new List<int> { 6, 7, 8, 9, 10 };
foo.AddRange(bar);
要替换,请在AddRange 之前添加foo.Clear();。当然,如果你知道第二个列表足够长,你可以在索引器上循环:
for(int i = 0 ; i < bar.Count ; i++) {
foo[i] = bar[i];
}
创建新的:
List<int> bar = new List<int>(foo);
【讨论】:
使用以 ICollection 作为参数的 ArrayList 的构造函数。 大多数集合都有这个构造函数。
ArrayList newList = new ArrayList(oldList);
【讨论】:
ArrayList model = new ArrayList();
ArrayList copy = new ArrayList(model);
?
【讨论】:
ArrayList l1=new ArrayList();
l1.Add("1");
l1.Add("2");
ArrayList l2=new ArrayList(l1);
【讨论】: