C# 如何在数据表的每一列中获取最大字符串长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1053560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:06:36  来源:igfitidea点击:

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

c#.netlinqdatatablemax

提问by Ronnie Overby

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

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

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

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

采纳答案by Mehrdad Afshari

The maximum string length for the whole table (assuming at least one non-null value there, otherwise, Maxwill throw an exception):

整个表的最大字符串长度(假设那里至少有一个非空值,否则Max将抛出异常):

int maxStringLength = dataTable.AsEnumerable()
                              .SelectMany(row => row.ItemArray.OfType<string>())
                              .Max(str => str.Length);

If you want maximum string length for eachcolumn, you could do (assuming at least one non-null value in each column, otherwise, Maxwill throw an exception):

如果您想要每一列的最大字符串长度,您可以这样做(假设每一列中至少有一个非空值,否则Max将引发异常):

List<int> maximumLengthForColumns = 
   Enumerable.Range(0, dataTable.Columns.Count)
             .Select(col => dataTable.AsEnumerable()
                                     .Select(row => row[col]).OfType<string>()
                                     .Max(val => val.Length)).ToList();

回答by roncansan

With c# 6, you can prevent the exception by adding val?.Length

使用 c# 6,您可以通过添加 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();