7

如何将一个 Arraylist 数据移动到另一个 Arraylist。我尝试了很多选项,但输出的形式是数组而不是数组列表

4

6 回答 6

16

首先 - 除非你在 .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);

要替换,foo.Clear();请在AddRange. 当然,如果你知道第二个列表足够长,你可以在索引器上循环:

    for(int i = 0 ; i < bar.Count ; i++) {
        foo[i] = bar[i];
    }

要创建新的:

    List<int> bar = new List<int>(foo);
于 2009-02-09T09:46:29.807 回答
6
        ArrayList model = new ArrayList();
        ArrayList copy = new ArrayList(model);

?

于 2009-02-09T09:44:32.883 回答
6

使用以 ICollection 作为参数的 ArrayList 的构造函数。大多数集合都有这个构造函数。

ArrayList newList = new ArrayList(oldList);
于 2009-02-09T09:44:52.943 回答
5
ArrayList l1=new ArrayList();
l1.Add("1");
l1.Add("2");
ArrayList l2=new ArrayList(l1);
于 2009-02-09T09:43:18.830 回答
1

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是正确的;)

于 2009-02-09T09:51:40.120 回答
1

我找到了向上移动数据的答案,例如:

Firstarray.AddRange(SecondArrary);
于 2009-02-09T09:57:53.477 回答