Ronnie Overby
Ronnie Overby

Reputation: 46470

How to get Max String Length in every Column of a Datatable

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

Answers (3)

Hemendr
Hemendr

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>

enter image description here

    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

Mehrdad Afshari
Mehrdad Afshari

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

roncansan
roncansan

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

Related Questions