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

如何在IlNumerics数组中查找符合条件的行 提取首列值为9的矩阵子集

C# 二维数组按指定列值提取对应行的实现方案

现有代码问题

  • 直接对double[,]二维数组调用Where方法会遍历数组内所有单个元素,最终只会返回所有值为9的独立元素,而非完整行数据
  • 单独提取第一列过滤只能得到匹配的列值,无法关联到对应的整行数据

实现方案

方案1:基础循环实现(兼容性最好,性能最优)

// 原始矩阵
double[,] A = new double[,] {
    { 1, 9, 20 },
    { 2, 11, 21 },
    { 9, 12, 21 },
    { 9, 13, 23 },
    { 9, 14, 24 },
    { 6, 15, 25 }
};

int totalRows = A.GetLength(0);
int totalCols = A.GetLength(1);
List<double[]> matchedRows = new List<double[]>();

// 逐行校验第一列取值
for (int i = 0; i < totalRows; i++)
{
    if (A[i, 0] == 9)
    {
        // 提取当前整行数据
        double[] currentRow = new double[totalCols];
        for (int j = 0; j < totalCols; j++)
        {
            currentRow[j] = A[i, j];
        }
        matchedRows.Add(currentRow);
    }
}

// 输出验证,结果和预期完全一致
foreach (var row in matchedRows)
{
    Console.WriteLine($"{{ {string.Join(", ", row)} }}");
}

如果需要最终返回二维数组格式,可以追加转换逻辑:

double[,] result2D = new double[matchedRows.Count, totalCols];
for (int i = 0; i < matchedRows.Count; i++)
{
    for (int j = 0; j < totalCols; j++)
    {
        result2D[i, j] = matchedRows[i][j];
    }
}

方案2:LINQ简化实现

using System.Linq;

var matchedRows = Enumerable.Range(0, A.GetLength(0))
                    .Select(rowIdx => Enumerable.Range(0, A.GetLength(1))
                                        .Select(colIdx => A[rowIdx, colIdx])
                                        .ToArray())
                    .Where(row => row[0] == 9)
                    .ToList();

输出结果

{ 9, 12, 21 }
{ 9, 13, 23 }
{ 9, 14, 24 }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 09:15:03