genespos
genespos

Reputation: 3311

Get the max length for each field of a DataTable

My goal is to show the whole content of a DataTable into a RichTextBox so I thought about using String.Format 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.

Upvotes: 0

Views: 3372

Answers (2)

Salah Akbari
Salah Akbari

Reputation: 39956

It should be something like this:

Dim maximumLengthForColumns As List(Of Integer) = Enumerable.Range(0, DataTable.Columns.Count).[Select](Function(col) dataTable.AsEnumerable().[Select](Function(row) row(col)).OfType(Of String)().Max(Function(val) val.Length)).ToList()

The formatted code is as below(this one is just for readability):

Dim maximumLengthForColumns As List(Of Integer) = Enumerable.Range(0, dataTableDataTable.Columns.Count)
                                                 .[Select](Function(col) dataTable.AsEnumerable()
                                                 .[Select](Function(row) row(col))
                                                 .OfType(Of String)().Max(Function(val) val.Length)).ToList()

Upvotes: 1

SSS
SSS

Reputation: 5403

'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
  lstMaxLen.Add(intMaxLen)
Next dcl

Upvotes: 0

Related Questions