Reputation: 46470
I have a DataTable object. Every column is of type string.
Using LINQ, how can I get the maximum string length for every column?
Upvotes: 11
Views: 27492
Reputation: 1038
If you want to consider maxLength for each column of table with multi line cell value. I have created one that return Dictionary<Column-Index, MaxLength>
private Dictionary<int, int> TableColumnWidth(DataTable dt)
{
Dictionary<int, int> result = new();
for (int i = 0; i < dt.Columns.Count; i++)
{
int maxLength = 0;
int cellLength = 0;
foreach (DataRow row in dt.Rows)
{
if (row[i] != DBNull.Value && !string.IsNullOrEmpty(row[i].ToString()))
{
cellLength = row[i].ToString().Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).Max(x => x.Length);
if (maxLength < cellLength)
{
maxLength= cellLength;
}
}
}
result.Add(i, maxLength);
}
return result;
}
Upvotes: 0
Reputation: 421988
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();
Upvotes: 21
Reputation: 2380
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();
Upvotes: 2