简体   繁体   中英

Conversion into jagged array from multidimensional array in C# console application?

I have console app looking to update the following code into jagged array. Should I use jagged key word etc?

 float[, ] tempsGrid = new float[4, 3];

        for (int x = 0; x < 4; x++)
        {
            for (int y = 0; y < 3; y++)
            {
                tempsGrid[x, y] = x + 10 * y;
             }
        }

        for (int x = 0; x < 4; x++)
        {
            for (int y = 0; y < 3; y++)
            {
                Console.Write(tempsGrid[x, y] + ", ");
            }
            Console.WriteLine();
        }

I might be mistaken, but if I understood your question correctly, you wanted to convert a multidimensional array into a jagged array. There is no predefined way to do this, you simply have to copy the values from the multi array into the jagged array:

public static T[][] ConvertToJagged<T>(T[,] multiArray)
{
    var fin = new T[multiArray.GetLength(0)][];
    for (var i = 0; i < multiArray.GetLength(0); i++)
    {
        fin[i] = new T[multiArray.GetLength(1)];
        for (var j = 0; j < multiArray.GetLength(1); j++)
            fin[i][j] = multiArray[i, j];
    }
    return fin;
}

I, personally, prefer generating arrays with a help of Linq :

   using System.Linq;

   ...

   float[][] tempsGrid = Enumerable
     .Range(0, 3)
     .Select(y => Enumerable
        .Range(0, 4)
        .Select(x => x + 10.0f * y)
        .ToArray())
     .ToArray();

   Console.Write(string.Join(Environment.NewLine, tempsGrid
     .Select(line => string.Join(", ", line)))); 

However, you may find this approach too complex. Good old for loops solution:

   int height = 4;
   int width = 3;

   float[][] tempsGrid = new float[height][];

   // I suggest reversing the logic: line - y - 1st index; column - x - 2nd index
   for (int y = 0; y < tempsGrid.Length; ++y) {
     tempsGrid[y] = new float[width];

     for (int x = 0; x < tempsGrid[y].Length; ++x)  
       tempsGrid[y][x] = x + 10 * y; 
   }

   for (int y = 0; y < tempsGrid.Length; ++y) {
     for (int x = 0; x < tempsGrid[y].Length; ++x)  
       Console.Write(tempsGrid[y][x] + ", ");

     Console.WriteLine();
   }   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM