You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何动态指定列数将Excel来源的double[,]数组转为锯齿数组?

Solution for Variable Column Selection in Matrix Conversion

Great question! Hardcoding column indices is a total pain when the number of columns can change—scalability is key here. Let's adjust your code to handle any number of columns cleanly, no manual index typing required.

Step 1: Define your target column count as a variable

First, set up a variable to hold the number of columns you want to select. This can be 13, 20, or any other value based on your use case:

// Replace with your desired column count (e.g., 20 for a larger dataset)
int targetColumnCount = 13;

Step 2: Generate column indices dynamically

Instead of listing every index manually, use Enumerable.Range to create a sequence of integers starting at 1 (since your original code starts at column 1) and running up to your target count. This creates exactly the index array you need:

// Produces an array like [1, 2, 3, ..., targetColumnCount]
int[] columnIndices = Enumerable.Range(1, targetColumnCount).ToArray();

Step 3: Update your matrix conversion code

Now just pass this dynamic index array to GetColumns instead of the hardcoded values. Your full, flexible code will look like this:

double[,] sourceMatrix = source.ToMatrix(out columnNames);
int targetColumnCount = 13; // Adjust this value as needed
int[] columnIndices = Enumerable.Range(1, targetColumnCount).ToArray();
double[][] inputs = sourceMatrix.GetColumns(columnIndices).ToJagged();

To avoid annoying index-out-of-range errors if your target count exceeds the actual columns in the matrix, add a quick validation step:

double[,] sourceMatrix = source.ToMatrix(out columnNames);
int targetColumnCount = 13;

// Make sure we don't request more columns than exist
if (targetColumnCount > sourceMatrix.GetLength(1))
{
    throw new ArgumentOutOfRangeException(nameof(targetColumnCount), 
        $"Target column count ({targetColumnCount}) exceeds available columns ({sourceMatrix.GetLength(1)}) in the source matrix.");
}

int[] columnIndices = Enumerable.Range(1, targetColumnCount).ToArray();
double[][] inputs = sourceMatrix.GetColumns(columnIndices).ToJagged();

Quick heads-up: Enumerable.Range lives in the System.Linq namespace, so make sure you have using System.Linq; at the top of your file if it's not already there.

内容的提问来源于stack exchange,提问作者user19754

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:18:32