如何从2D数组中提取特定列

时间:2016-11-22 17:54:34

标签: c# arrays

我有一个数组,我想从中提取特定列,让我们只说第3列。

示例:

  

1 2 3 4
  1 2 3 4
  1 2 3 4
  1 2 3 4

想要的是提取第3列并仅显示:

  

3
  3
  3
  3

这是我的代码,我可以在其中创建用户指定的动态数组:

int r;
int c;
Console.Write("Enter number of rows: ");
r = (int)Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number of columns: ");
c = (int)Convert.ToInt32(Console.ReadLine());
int[,] matrix = new int[r, c];

/*Insert Values into Main Matrix
 --------------------------------------------------------------------------------*/
for (int row = 0; row < r; row++)
{
    for (int col = 0; col < c; col++)
    {
        Console.Write("Enter value for matrix[{0},{1}] = ",row, col);
        matrix[row, col] = (int)Convert.ToInt32(Console.ReadLine());
    }
}


/*Print and show initial Matrix
 --------------------------------------------------------------------------------*/
Console.WriteLine("Your matrix is,");
for (int row = 0; row < r; row++)
{
    for (int col = 0; col < c; col++)
    {
        Console.Write(matrix[row, col] + " ");
    }
    Console.WriteLine();
}


/*Fixing first 2 columns
 --------------------------------------------------------------------------------*/
int startingMatrixCols = 2;
Console.WriteLine("Fixed first 2 columns:");
for (int row = 0; row < r; row++)
{
    for (int col = 0; col < startingMatrixCols; col++)
    {
        Console.Write(matrix[row, col] + " ");
    }
    Console.WriteLine();
}

2 个答案:

答案 0 :(得分:1)

    var column = 2; // your expected column
    //if it needs to be dynamic, you can read it from user entry
    // Console.Write("Enter expected column: ");
    // column = int.Parse(Console.ReadLine()); //enhance with error checks
    for (int row = 0; row < r; row++)
    {
        Console.Write(matrix[row, column] + " ");
    }

答案 1 :(得分:-2)

Console.Write("Enter the column number to display ");
int displayColNo = (int)Convert.ToInt32(Console.ReadLine());

/*If displayColNo=3 it displays only 3rd column numbers*/
for (int row = 0; row < r; row++)
{
    Console.Write(matrix[row, displayColNo]);
    Console.WriteLine();
}