【问题标题】:Move one arraylist data to another arraylist in C#在C#中将一个arraylist数据移动到另一个arraylist
【发布时间】:2010-10-06 08:49:29
【问题描述】:

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

【问题讨论】:

  • 您想要元素的深拷贝还是浅拷贝?

标签: c# arraylist


【解决方案1】:

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

Firstarray.AddRange(SecondArrary);

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      首先 - 除非您使用 .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);
      

      【讨论】:

      • 除非使用 .NET 1.1,否则为什么建议使用 List 而不是 ArrayList??
      • @kashif 类型安全(避免愚蠢的错误)、性能(装箱和内存)、更好的 API、对 LINQ 的支持等等......为什么不会有人更喜欢通用版?我在这里知道的唯一边缘情况是 Hashtable,它仍然保留了一些用法,因为它具有比 Dictionary`2 更好的线程模型
      【解决方案4】:

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

      ArrayList newList = new ArrayList(oldList);
      

      【讨论】:

        【解决方案5】:
                ArrayList model = new ArrayList();
                ArrayList copy = new ArrayList(model);
        

        ?

        【讨论】:

          【解决方案6】:
          ArrayList l1=new ArrayList();
          l1.Add("1");
          l1.Add("2");
          ArrayList l2=new ArrayList(l1);
          

          【讨论】:

            猜你喜欢
            • 2014-03-18
            • 1970-01-01
            • 2012-06-30
            • 2015-03-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-05-19
            相关资源
            最近更新 更多