|
dev
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
create string array from dataread resultsI 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?
Show quote
"Chuck P" <Chuck@newsgroup.nospam> wrote in message Not really. That's what I would do. Remember the array and ArrayList just 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? contain references to the strings, not copies. David 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. Chuck P wrote:
> I need to create a string array from a datareader in .net 2.0 Bug: The size of the array should be the same as the size of the list.> 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); The ArrayList class is made almost obsolete by generics. Use a > > return str; > > Is their a better way? 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(); |
|||||||||||||||||||||||