ใช้ Nested Loop วนลูปผ่าน 2D Array และเก็บค่าลง 1D Array ตามลำดับ
โค้ดตัวอย่างเต็ม
using System;
namespace Program
{
class TwoDMatrix
{
static void Main(string[] args)
{
// 2D Array 2x2
int[,] a = new int[2, 2]
{
{1, 2},
{3, 4}
};
int[] b = new int[4]; // 1D Array ขนาด 4
int k = 0;
Console.WriteLine("Two-Dimensional Array...");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i, j]);
}
}
// แปลง 2D -> 1D (Row-major order)
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
b[k++] = a[i, j];
}
}
Console.WriteLine("One-Dimensional Array...");
for (int i = 0; i < 4; i++)
{
Console.WriteLine("b[{0}] = {1}", i, b[i]);
}
Console.ReadKey();
}
}
}
ผลลัพธ์
Two-Dimensional Array... a[0,0] = 1 a[0,1] = 2 a[1,0] = 3 a[1,1] = 4 One-Dimensional Array... b[0] = 1 b[1] = 2 b[2] = 3 b[3] = 4
วิธีอื่น: ใช้ LINQ (C# 3.0+)
using System.Linq; int[] flat = a.Cast<int>().ToArray();
วิธีอื่น: Buffer.BlockCopy (เร็วกว่าสำหรับ Primitive Types)
using System; int[] flat = new int[4]; Buffer.BlockCopy(a, 0, flat, 0, 4 * sizeof(int));