Build a dynamic array from DataReader...

B

Brent

I'm having a hard time wrapping my head around how to build a
multi-dimensional array of n length out of a DataReader loop. Take this
pseudo-code:

=======================================
public string[,] get_array(string sql)
{

//create db connection & open

string[,] arrReturn = new String[,];

SqlDataReader dataReader = myCommand.ExecuteReader();

if (dataReader.HasRows)
{
while (dataReader.Read())
{
//next line I don't know what to do!
arrReturn.AddToArray = {dataReader[0].ToString(),
dataReader[1].ToString()};
}
}

myConn.Close();
return arrReturn;
}
========================================

I can't seem to find anything in my Google searches that relates to
this. ArrayList seems only to work for unidimensional arrays, while
Array.CreateInstance requires that I know the array size before
populating it (which a datareader can't give me).

I'd sure appreciate any help!

--Brent
 
B

Bruce Barker

a jagged (array of arrays) might make more sense. easiest is an araylist of
string arrays.

//create db connection & open

ArrayList al = new ArrayList();

SqlDataReader dataReader = myCommand.ExecuteReader();

if (dataReader.HasRows)
{
while (dataReader.Read())
{
string[] fields = new string[datareader.FieldCount];
for (int i =0; i < datareader.FieldCount; ++i)
fields = dataReader.ToString() ;
al .Add(fields);
}
}
string [][] arrReturn = (string[][]) al .ToArray(string[]);

//print
for (int row=0; row<arrReturn.Count; ++ row)
for (int col=0; col < arrReturn[row].Length; ++col)
print (arrReturn[row][col]);


-- bruce (sqlwork.com)
 

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

Top