代码之家  ›  专栏  ›  技术社区  ›  balaweblog

在C中将一个arraylist数据移动到另一个arraylist#

  •  7
  • balaweblog  · 技术社区  · 16 年前

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

    6 回复  |  直到 16 年前
        1
  •  16
  •   Marc Gravell    16 年前

    首先-除非你在.NET 1.1上,否则你应该避免 ArrayList -首选类型化集合,如 List<T> .

    当你说“复制”的时候-你想 代替 , 追加 ,或 新建 ?

    用于追加(使用 列表<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);
    
        2
  •  6
  •   Konstantin Savelev Stephen Cleary    16 年前
            ArrayList model = new ArrayList();
            ArrayList copy = new ArrayList(model);
    

    ?

        3
  •  6
  •   bang    16 年前

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

    ArrayList newList = new ArrayList(oldList);
    
        4
  •  5
  •   Øyvind Skaar    16 年前
    ArrayList l1=new ArrayList();
    l1.Add("1");
    l1.Add("2");
    ArrayList l2=new ArrayList(l1);
    
        5
  •  1
  •   Community CDub    8 年前

    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 是spot on;)

        6
  •  1
  •   ridoy Ali Umair    11 年前

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

    Firstarray.AddRange(SecondArrary);