如何在数组[] [,]和[,] []中输入和输出值(锯齿状数组和多维数组的混合)

时间:2019-03-11 19:44:44

标签: c# multidimensional-array jagged-arrays

我正在尝试改进有关如何在多维数组中查找项目的代码,因为当我增加数据量时,我想避免将来可能出现的性能问题。我是编程的新手,所以有很多我不知道的东西。我一直在主题多维数组,锯齿状数组,排序方面进行大量搜索。我想我需要使用锯齿状数组,因为我需要排序才能找到第三大和第六大的数字。但是我意识到我必须寻求有关示例的帮助或链接到更多信息,因为在定义锯齿状数组时遇到了问题。我将尝试隔离每个问题,因为我被困在我相信对那些比我更熟悉阵列的人来说容易的事情上。应该可以根据jagged-arrays

混合锯齿状数组和多维数组

以下是[] []有效的示例

using System;
using System.Collections;
namespace SortJaggedArray
{
class host
{
    [STAThread]
    static void Main(string[] args)
    {
        int[][] arr = new int[2][];
        arr[0] = new int[3] {1,5,3};
        arr[1] = new int[4] {4,2,8,6};

        // Write out a header for the output.
        Console.WriteLine("Array - Unsorted\n");

        for (int i = 0; i < arr.Length; i++)
        {
             System.Console.WriteLine("Outer array " + i);

             for (int j = 0; j < arr[i].Length; j++)
             {
                  System.Console.Write(arr[i][j] + " ");
             }
             System.Console.WriteLine(" ");
             System.Console.WriteLine(" ");
        }
        Console.ReadLine();
    }
}
}

//Output:
//Outer array 0
//1 5 3

//Outer array 1
//4 2 8 6

以下是我的[] [,]示例,其中输入有效,但我在如何编写输出方面遇到困难:

using System;
using System.Collections;
namespace SortJaggedArray
{
    class host
    {
        [STAThread]
        static void Main(string[] args)
        {
            int[][,] arr = new int[2][,]
            {
                new int[,] { { 1, 3 }, { 5, 2 }, { 3, 9 } },
                new int[,] { { 4, 1 }, { 2, 7 }, { 8, 5 }, { 6, 3 } }
            };
            // Write out a header for the output.
            Console.WriteLine("Array - Unsorted\n");

            foreach (int i in arr)
                Console.WriteLine(i);

            Console.ReadLine();
        }
    }
}

Wanted output:
Nr 0: 
1, 3
5, 2
3, 9

Nr 1:
4, 1
2, 7
8, 5
6, 3

问题1: 如何编写WriteLine / for / foreach以查看锯齿状数组[] [,]的内容?

问题2: 我想将其更改为[,] [],但随后出现如何在这种锯齿状数组中输入/输出数据的问题。如何输入数据?如何Writeline / for / forarch查看锯齿状数组[,] []的内容?

1 个答案:

答案 0 :(得分:0)

您需要遍历每个维度:

for(int i=0; i<arr.Length; i++){
    Console.WriteLine($"Nr {i}:");
    for(int j=0;j<arr[i].GetLength(0);j++){
        for(int k=0;k<arr[i].GetLength(1);k++){
            Console.Write($"{arr[i][j,k]} ");
        }
        Console.WriteLine();
    }
    Console.WriteLine();
}

输出:

Nr 0:
1 3 
5 2 
3 9 

Nr 1:
4 1 
2 7 
8 5 
6 3