c# - List<string[]> 通过 Linq 确定最大长度

标签 c# linq list

我有以下结构

List<string[]> sList = new List<string[]>() {
    new[] { "x", "xxx", "xxxx" },  //1,3,4
    new[] { "x", "xx", "xx" },     //1,2,2
    new[] { "xxxxxx", "xx", "xx" } //6,2,2
};

我需要按列确定项目的最大string.length

在这个例子中,预期结果应该是:

List<int> Result = new List<int>() { 6, 3, 4 };

是否有简单的 Linq 方法?

我的努力(工作但不使用 Linq):

List<int> Result = new List<int>();
foreach (string[] line in Table)
{
    for (int i = 0; i < line.Length; i++)
    {
        if (Result.Count > i)
        {
            if (Result[i] < line[i].Length)
            {
                Result[i] = line[i].Length;
            }
        }
        else
        {
            Result.Insert(i, line[i].Length);
        }
    }
}

行数/列数是动态的,但每行的列数相同。

最佳答案

这是我能想到的最好的:

List<int> Result = sList.First().Select((x, i) => sList.Max(y => y[i].Length)).ToList();

一行加分?

解释: 既然你说过它们都有相同数量的元素,那么就拿第一行并循环遍历它。使用索引从其他每一行获取该元素,获取长度,然后获取该元素的最大值。

关于c# - List<string[]> 通过 Linq 确定最大长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32716761/

相关文章:

C#在switch语句中执行所有case

c# - 如何创建对象的内部搜索引擎

c# - 取消 NamedPipeClientStream.Read 调用

c# - 加快 MSBuild 构建过程

c# - 使用 LinQ 过滤 ObservableCollection

c# - 返回结果还是先放到变量中?

c# - 使用 .Contains 保留 LINQ 的顺序

python-3.x - 在新的数据帧上自动提取两个Python字符串之间的相等性

python - 如何使用给定列表创建分页函数

PHP 和 MySQL - 回显字符串列表