如何动态指定列数将Excel来源的double[,]数组转为锯齿数组?
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();
Bonus: Add a safety check (optional but recommended)
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

