Home All Groups Group Topic Archive Search About

create string array from dataread results

Author
28 Feb 2007 10:43 PM
Chuck P
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?

Author
28 Feb 2007 11:51 PM
David Browne
Show quote
"Chuck P" <Chuck@newsgroup.nospam> wrote in message
news:171A5400-F7D6-4D72-A8DB-9DEF1B9BCDB1@microsoft.com...
>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
Author
1 Mar 2007 5:16 AM
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.
Author
28 Feb 2007 11:56 PM
Göran Andersson
Chuck P wrote:
> 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();


--
Göran Andersson
_____
http://www.guffa.com

AddThis Social Bookmark Button