Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi everyone!

I want to know if there's another way to copy an ArrayList to another without using a foreach loop.

I tried this:
MyOldArraylist = new ArrayList(MyNewArraylist);


It works, but i don't know if its a good idea or not doing this.



Thanks beforehead!
Posted
Updated 4-Sep-13 4:13am
v2

 
Share this answer
 
Hi you can refer this code for copying one array list to another in c#

C#
System.Collections.ArrayList OriginalArrList = new System.Collections.ArrayList();
System.Collections.ArrayList CopyArrayList = new System.Collections.ArrayList();
OriginalArrList.Add("1234");
OriginalArrList.Add("123");
OriginalArrList.Add("12");
OriginalArrList.Add("1");
OriginalArrList.Add("xyz");
 
CopyArrayList.Add(OriginalArrList.Clone());


You can reach to article:


http://www.authorcode.com/code-sample-copy-one-arraylist-to-another-arraylist-in-c/

Regards,
mubin
 
Share this answer
 
v3
I think your approach is one of the right one.
I show you a different approach like:
C#
OriginalArrList = new System.Collections.ArrayList();
 CopyArrayList = new System.Collections.ArrayList();
 OriginalArrList.Add("1234");
 OriginalArrList.Add("123");
 OriginalArrList.Add("12");
 OriginalArrList.Add("1");
 OriginalArrList.Add("xyz");
 
 CopyArrayList.Add(OriginalArrList.Clone());

Or,
C#
ArrayList a = new ArrayList();
ArrayList b = new ArrayList();

b.AddRange(a);
 
Share this answer
 
v3
Here's a little example, to show you how it works:

C#
public partial class MainWindow : Window
    {
        private string[] arrayToCopy;
        private string[] newArray;

        public MainWindow()
        {
            InitializeComponent();

            arrayToCopy = new string[] { "A", "B", "C", "D", "E" };
            newArray = new string[5] {"","","","","" };

            CopyArray();
        }

        public void CopyArray()
        {
            arrayToCopy.CopyTo(newArray, 0);
        }
    }


Hope it helps a little bit :)
 
Share this answer
 
In addition to other answers:

You should not use the type ArrayList at all. It is obsolete. Instead, use System.Collections.Generic.List<>, which would not compromise performance. Non-generic non-specialized collection types have been rendered obsolete as early as of .NET Framework v.2.0, when generics were introduced. They eliminated potentially dangerous type casting. Non-generic collection types were not formally marked obsolete just because there is nothing wrong with using them in legacy projects, for better backward compatibility, but using them in new development makes no sense at all.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900