create string array from dataread results

  • Thread starter Thread starter Guest
  • Start date Start date
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?
 
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
 
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();
 
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.
 
Back
Top