如何在数据表的每一列中获取最大字符串长度 [英] How to get Max String Length in every Column of a Datatable

查看:14
本文介绍了如何在数据表的每一列中获取最大字符串长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DataTable 对象.每列都是字符串类型.

I have a DataTable object. Every column is of type string.

使用 LINQ,如何获得每列的最大字符串长度?

Using LINQ, how can I get the maximum string length for every column?

推荐答案

整表的最大字符串长度:

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();

这篇关于如何在数据表的每一列中获取最大字符串长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆