genespos genespos - 1 year ago 151 Question

Get the max length for each field of a DataTable

My goal is to show the whole content of a

into a
so I thought about using
to make columns but I need to know the max length of contents for each Column.

I found the below C# code on SO but I was unable to translate it to VB.Net:

List<int> maximumLengthForColumns = Enumerable.Range(0, dataTable.Columns.Count)
.Select(col => dataTable.AsEnumerable()
.Select(row => row[col]).OfType<string>()
.Max(val => val.Length)).ToList();

Any hint on any different (and easier or better) way to reach my goal is appreciated.

Answer Source
'dtb is the datatable'
Dim lstMaxLen As New List(Of Integer)
For Each dcl As DataColumn In dtb.Columns
  Dim intMaxLen As Integer = 0
  For Each drw As DataRow In dtb.Rows
    If drw(dcl.ColumnName).ToString.Length > intMaxLen Then
      intMaxLen = drw(dcl.ColumnName).ToString.Length
    End If
  Next drw
Next dcl
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download