A better way of getting a data table with various column types into string array

Posted by Vlad on Stack Overflow See other posts from Stack Overflow or by Vlad
Published on 2010-06-08T19:47:46Z Indexed on 2010/06/08 19:52 UTC
Read the original article Hit count: 196

Filed under:
|

This should be an easy one, looks like I got myself too confused.

I get a table from a database, data ranges from varchar to int to Null values. Cheap and dirty way of converting this into a tab-delimited file that I already have is this (shrunken to preserve space, ugliness is kept on par with original):

da.Fill(dt)
' da - DataAdapter '
' dt - DataTable '
Dim lColumns As Long = dt.Columns.Count
Dim arrColumns(dt.Columns.Count) As String
Dim arrData(dt.Columns.Count) As Object

Dim j As Long = 0
Dim arrData(dt.Columns.Count) As Object

For i = 0 To dt.Rows.Count - 1

    arrData = dt.Rows(i).ItemArray()

    For j = 0 To arrData.GetUpperBound(0) - 1
        arrColumns(j) = arrData(j).ToString
    Next

  wrtOutput.WriteLine(String.Join(strFieldDelimiter, arrColumns))

  Array.Clear(arrColumns, 0, arrColumns.GetLength(0))
  Array.Clear(arrData, 0, arrData.GetLength(0))
Next

Not only this is ugly and inefficient, it is also getting on my nerves. Besides, I want, if possible, to avoid the infamous double-loop through the table. I would really appreciate a clean and safe way of rewriting this piece.

I like the approach that is used here - especially that is trying to solve the same problem that I have, but it crashes on me when I apply it to my case directly.

© Stack Overflow or respective owner

Related posts about vb.net

Related posts about parsing