gpt4 book ai didi

c# - List 通过 Linq 确定最大长度

转载 作者:IT王子 更新时间:2023-10-29 04:40:40 26 4
gpt4 key购买 nike

我有以下结构

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com