create string array from dataread results

G

Guest

I need to create a string array from a datareader in .net 2.0
I am using this:

ArrayList al = new ArrayList();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
al.Add(dr.GetString(0));
}
}
string[] str = new string[al.Count - 1];
al.CopyTo(str);

return str;

Is their a better way?
 
D

David Browne

Chuck P said:
I need to create a string array from a datareader in .net 2.0
I am using this:

ArrayList al = new ArrayList();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
al.Add(dr.GetString(0));
}
}
string[] str = new string[al.Count - 1];
al.CopyTo(str);

return str;

Is their a better way?

Not really. That's what I would do. Remember the array and ArrayList just
contain references to the strings, not copies.

David
 
G

Guest

Chuck said:
I need to create a string array from a datareader in .net 2.0
I am using this:

ArrayList al = new ArrayList();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
al.Add(dr.GetString(0));
}
}
string[] str = new string[al.Count - 1];

Bug: The size of the array should be the same as the size of the list.
al.CopyTo(str);

return str;

Is their a better way?

The ArrayList class is made almost obsolete by generics. Use a
List<string> instead. The List.ToArray method returns an array of the
same type used for the list, so for a List<string> it returns a string
array:

List<string> al = new List<string>();
using (SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read()) {
al.Add(dr.GetString(0));
}
}
return al.ToArray();
 
S

Steven Cheng[MSFT]

Hello Chuck,

I also think your current approach reasonable. If you have want, you can
also try the generic List<T> (instead of ArrayList) for compare and
determine which one to use. Using generic List<T> here can ensure
strong-typed collection access which avoid type casting.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead


This posting is provided "AS IS" with no warranties, and confers no rights.
 

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