Increasing an array dynamically  
Author Message
NewbieDude





PostPosted: Visual C# General, Increasing an array dynamically Top

hey there,

I want to declare a single dimentional array somewhere and then increase its size dynamically inside a foreach loop.

e.g.:

//declare array2

foreach int i in array1

{

//increase size of array2
}




Visual C#14  
 
 
PJ. van de Sande





PostPosted: Visual C# General, Increasing an array dynamically Top

You can use the ArrayList class, this array will automaticly grow when you add a new element.


 
 
PJ. van de Sande





PostPosted: Visual C# General, Increasing an array dynamically Top

About your question, here is a little example how to encrease the size of an array:


Int32[] source = GetArraySource();
Int32[] dest = new Int32[];

foreach( Int32 i in source )
{
Int32[] temp = new Int32[ dest.Length + 1 ];
dest.CopyTo( temp, 0 );

temp[ temp.Length -1 ] = i;
dest = temp;
}




 
 
niroshanonline





PostPosted: Visual C# General, Increasing an array dynamically Top

you can user the array list for this ..

private ArrayList m_list = new ArrayList();

steve

www.igetcertified.com


 
 
pfitzsimons





PostPosted: Visual C# General, Increasing an array dynamically Top

Array.Resize is 2.0 does the job:

int[] array2 ...

Array.Resize(ref array2, array2.Length);


 
 
CalvinR





PostPosted: Visual C# General, Increasing an array dynamically Top

This would work to increase the size of the array however depending on how many items you have in the array it could be kind of slow, you might want to look into using a linked list class. They aren't as efficient as arrays for searching for items but you can't beat them when it comes to increasing the number of items to store.
 
 
Muggins





PostPosted: Visual C# General, Increasing an array dynamically Top

wow! something borrowed from VB, looks v.good.