tags:

views:

23

answers:

1

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.

A: 

You should be able to do just like this:

File.WriteAllText( _
  fileName, _
  String.Join( _
    Environment.NewLine, _
    dt.Rows.Cast(Of DataRow)().Select( _
      Function(r) String.Join( _
        ",", _
        r.ItemArray().Select(Function(o) o.ToString()).ToArray() _
      ) _
    ).ToArray() _
  ) _
)
Guffa
Amazing! Not only this is exactly what I had in mind, but was unable to achieve, it actually worked from the first run. You, sir, are now my personal hero :)
Vlad