C#中如何将二维List<>的各列求和结果存入一维List<>
二维List按列求和实现逻辑指导
核心实现逻辑
- 第一步:边界校验,判断二维List是否为空、内部是否存在有效子列表,避免后续下标越界
- 第二步:确认总列数,常规场景下取第一个子列表的长度即可;如果要兼容不等长子列表的情况,遍历所有子列表取最大长度作为总列数
- 第三步:初始化存储结果的一维List,长度等于总列数,所有元素初始值设为0
- 第四步:外层循环遍历列索引,范围从0到总列数-1
- 第五步:内层循环遍历二维List的每一行,取出当前行对应列索引的元素,累加到结果List对应索引的位置上
注意和按行求和的逻辑差异:按行求和时外层遍历行索引、内层遍历列索引,按列求和需要调换两层循环的顺序
示例代码(Java为例)
import java.util.ArrayList; import java.util.List; public class ColumnSumCalculator { public static void main(String[] args) { // 示例二维List List<List<Integer>> twoDimensionalList = new ArrayList<>(); twoDimensionalList.add(List.of(1, 2, 3)); twoDimensionalList.add(List.of(4, 5, 6)); twoDimensionalList.add(List.of(7, 8, 9)); // 边界校验 if (twoDimensionalList.isEmpty()) { System.out.println(new ArrayList<>()); return; } // 取总列数,兼容不等长子列表场景 int maxColumnCount = 0; for (List<Integer> row : twoDimensionalList) { maxColumnCount = Math.max(maxColumnCount, row.size()); } // 初始化结果列表 List<Integer> columnSumResult = new ArrayList<>(); for (int i = 0; i < maxColumnCount; i++) { columnSumResult.add(0); } // 按列遍历累加 for (int colIndex = 0; colIndex < maxColumnCount; colIndex++) { for (List<Integer> row : twoDimensionalList) { // 子列表长度不足时跳过(相当于加0) if (colIndex < row.size()) { columnSumResult.set(colIndex, columnSumResult.get(colIndex) + row.get(colIndex)); } } } // 输出示例结果:[12, 15, 18] System.out.println(columnSumResult); } }
常见问题避坑
- 不要直接默认所有子列表长度相同,一定要加列索引的边界判断,否则会抛出
IndexOutOfBoundsException - 结果List必须提前初始化对应长度的初始值,不要直接用
add方法赋值,否则会出现下标越界或者结果顺序错误 - 如果二维List存储的是浮点类型数据,只需要把
Integer替换为对应浮点类型即可,逻辑完全一致
内容的提问来源于stack exchange,提问作者chicacherry
相关产品推荐
相关产品推荐

