How to get around Array reference values

  • Thread starter Thread starter Jeff User
  • Start date Start date
J

Jeff User

I want to convert each record read (with a datareader) to a string
array and then place each of those arrays into another array (sResult)

The problem here is that when the inner loop begins to process the 2nd
record read (from the outer loop) & for example: iRowCnt ==1), the
values in sResult[0] are updated to reflect the new values being
placed into sRow.

OK, so I take it that when storing sRow into sResult, I am storing a
reference to sRow. The question is, how do I store the actual values
from each individual row into sResult?

string[][] sResult = new String[30][];
string[] sRow = new String[20];

//loop thru data reader
while(LocalReader.Read())
{
cnt=0;
iReaderLength = LocalReader.FieldCount;
while (cnt < iReaderLength)
{
sRow[cnt] = LocalReader.GetValue(cnt).ToString();
cnt++;
}
sResult[iRowCnt]=sRow;
iRowCnt++;
}

Hope this is clear
Jeff
 
Just move the statement where you create the new sRow, to create a new
one each time around the loop:

string[][] sResult = new String[30][];

//loop thru data reader
while(LocalReader.Read())
{
cnt=0;
iReaderLength = LocalReader.FieldCount;
string[] sRow = new String[iReaderLength];
while (cnt < iReaderLength)
{
sRow[cnt] = LocalReader.GetValue(cnt).ToString();
cnt++;
}
sResult[iRowCnt]=sRow;
iRowCnt++;
}


As well, you probably want to make sResult an ArrayList, then convert
it to an array at the end, so you never run over your 30 allocated
rows, and you never use less than 30 and leave nulls:

ArrayList sResult = new ArrayList();

//loop thru data reader
while(LocalReader.Read())
{
cnt=0;
iReaderLength = LocalReader.FieldCount;
string[] sRow = new String[iReaderLength];
while (cnt < iReaderLength)
{
sRow[cnt] = LocalReader.GetValue(cnt).ToString();
cnt++;
}
sResult.Add(sRow);
}

string[][] sResultArray =
(string[][])sResult.ToArray(typeof(string[]));

Now sResultArray will contain exactly the number of sRows that you read
in.
 

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

Back
Top