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
6 Answers
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);
2 Comments
kashif
why did you recommend using List<T> instead of ArrayList unless using .NET 1.1???
Marc Gravell
@kashif type safety (avoiding stupid bugs), performance (boxing and memory), better API, support for LINQ, etc... Why wouldn't someone prefer the generic version? The only edge case I know about here is Hashtable, which still retains some usage because it has a much better threading model than Dictionary`2
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 ;)