Arrays

  • Thread starter Thread starter Robert Bravery
  • Start date Start date
R

Robert Bravery

Hi all,

I have initialised an array with out length
I want to loop throu a data table and ad values froma column into the array,
to be used elswhere.
foreach (DataRow drview in dtview.Rows)
{
I want to add another item to the periods array
}

Or if I have to have the array's length predefined, how do I increas its
length after creation

Thanks
Robert
 
Robert,
Or if I have to have the array's length predefined, how do I increas its
length after creation

Arrays always hava a fixed length. If you want a list with dynamic
size, use a type such as ArrayList or List<T>. You can then call the
ToArray method to return an array after you've added all items.


Mattias
 
Robert said:
Hi all,

I have initialised an array with out length
I want to loop throu a data table and ad values froma column into the
array, to be used elswhere.
foreach (DataRow drview in dtview.Rows)
{
I want to add another item to the periods array
}

Or if I have to have the array's length predefined, how do I increas its
length after creation

Thanks
Robert

Hi Robert,

You can either initialise the array with the correct number of entries, i.e.
you know the number of rows you have, by means of the dtview.Rows
collection. Or you can use a generic list (or if in .NET < 2.0, an
ArrayList).

The list's have a ToArray method, which will return an array of the items
you've added so far.

Generally, resizing an array is slow, but if you're interested, it may look
something like this:

So, given our array to resize, we make a swap buffer of the new length, and
copy all the data from 'arrayToSize' into it, then we swap the swap buffer
into the original array.

///
byte[] arrayToSize = new byte[100];
int newLength = 200;

byte[] swapBuffer = new byte[100 + newLength];
arrayToSize.CopyTo( swapBuffer, 0 );
arrayToSize = swapBuffer;
///
 
You can use the static Array.Resize method.
Although as the other posters mentioned, the generic List<T> is more
appropriate for this.
--
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
Instant C++: C#/VB to C++ converter
C# Code Metrics: Quick metrics for C#
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Pointers to arrays 5
New array of dataRow[] 8
cast problem 1
Access Accessing arrays within loop - VBA 1
Arrays 22
passing array of structs to unmanaged code 2
Problem with byte array.... 1
Array index 5

Back
Top