title: I can't get correct max(len(fieldname)) of CSV file using Linq, SQL or MaxLength
body: <p>I am trying to import a csv file and I need to get the maximum field length so I know how large to make my varchar field in the new table.</p>
  
  <p>I have a small table with the longest text value of 315. Here is a logical description of what is happening:</p>
  
  <pre><code>If Len(Field) &gt; 255 And RowNumOf315Record &gt; 25 Then FieldLen = 255
  If Len(Field) &gt; 255 And RowNumOf315Record &lt;= 25 Then FieldLen = 315
  </code></pre>
  
  <p>If we nuke all records with the field length > 255 then the correct length is always returned.</p>
  
  <p>I tried Linq:</p>
  
  <pre><code>Table.Rows.Cast(Of DataRow)().Aggregate(0, Function(current, dRow) Math.Max(current, dRow("STAFF_ID_LAST_UPDT").ToString.Length))
  </code></pre>
  
  <p>I tried a direct query with ADODB:</p>
  
  <pre><code>    Dim rsLength As New ADODB.Recordset
      Dim connX As New ADODB.Connection
  
      connX.Open("Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=d:\EnvironProcessing\Q2_2016\MN\ust\;Extensions=csv,tab,txt;")
      rsLength.Open("select max(len([STAFF_ID_LAST_UPDT])) as l from [ff_other_liable_leaksites.txt]", connX)
      rsLength.MoveFirst()
      FieldLength = rsLength.Fields("l").Value
      rsLength.Close()
  </code></pre>
  
  <p>I tried using Column.MaxLength:</p>
  
  <pre><code>    SourceAdapter.Fill(Table)
      SourceAdapter.FillSchema(Table, SchemaType.Source)
      FieldLength3 = Int(Table.Columns(x).MaxLength / 2)
  </code></pre>
  
  <p>I know that ODBC determines the field type by looking at only the first 25 or so records so I get why FillSchema would fail. But when I am querying the entire table directly or with Linq with an aggregate function, it should actually read the entire table, right?</p>
  
  <p>If I do a Sum or an Avg aggregate it reads the entire dataset.</p>