How to get Max String Length in every Column of a Datatable
23,243
Solution 1
The maximum string length for the whole table:
int? maxStringLength = dataTable.AsEnumerable()
.SelectMany(row => row.ItemArray.OfType<string>())
.Max(str => str?.Length);
If you want maximum string length for each column, you could do:
List<int?> maximumLengthForColumns =
Enumerable.Range(0, dataTable.Columns.Count)
.Select(col => dataTable.AsEnumerable()
.Select(row => row[col]).OfType<string>()
.Max(val => val?.Length)
).ToList();
Solution 2
With c# 6, you can prevent the exception by adding val?.Length
var maximumLengthForColumns =
Enumerable.Range(0, dt.Columns.Count)
.Select(col => dt.AsEnumerable()
.Select(row => row[col]).OfType<string>()
.Max(val => val?.Length )).ToList();
Author by
MsBao
Updated on July 09, 2022Comments
-
MsBao almost 2 years
I have a DataTable object. Every column is of type string.
Using LINQ, how can I get the maximum string length for every column?
-
MsBao almost 15 yearsThat gets the length of the longest string in the whole table. I need the lengths of the longest strings in every column.
-
Fandango68 over 5 yearsDon't you mean IEnumerable? Enumerable is undefined in C#
-
Mehdi Anis about 4 yearsCode from @roncansan works great. However how can I get {ColumnName, MaxLength} pair in the "var maximumLengthForColumns"? OR Is it "Guranteed" that the MaxLength values in the "var maximumLengthForColumns" will be in exact order of the Columns in the table. Thanks.