How to move one Arraylist data to another arraylist. I have tried for many option but the output is in the form of array not arraylist
ArrayList l1=new ArrayList();
l1.Add("1");
l1.Add("2");
ArrayList l2=new ArrayList(l1);
ArrayList model = new ArrayList();
ArrayList copy = new ArrayList(model);
?
Use the constructor of the ArrayList that takes an ICollection as a parameter. Most of the collections have this constructor.
ArrayList newList = new ArrayList(oldList);
First - unless you are on .NET 1.1, you should a avoid ArrayList
- prefer typed collections such as List<T>
.
When you say "copy" - do you want to replace, append, or create new?
For append (using 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);
To replace, add a foo.Clear();
before the AddRange
. Of course, if you know the second list is long enough, you could loop on the indexer:
for(int i = 0 ; i < bar.Count ; i++) {
foo[i] = bar[i];
}
To create new:
List<int> bar = new List<int>(foo);
If you use ArrayList newList = new ArrayList(oldList); and the oldlist holds reference values (like classes) will they be copied or will the reference be copied?
http://msdn.microsoft.com/en-us/library/system.collections.arraylist.addrange.aspx
shameless copy/paste from the above link
// 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' );
Other than that I think Marc Gravell is spot on ;)
I found the answer for moving up the datas
Firstarray.AddRange(SecondArrary)