溫馨提示×

C#中二維數組與其他數據結構的轉換

c#
小樊
125
2024-09-16 08:46:11
欄目: 編程語言

在C#中,二維數組可以與其他數據結構(如列表、字典等)進行轉換

  1. 二維數組轉換為列表(List):
int[,] array = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
List<List<int>> list = new List<List<int>>();

for (int i = 0; i< array.GetLength(0); i++)
{
    List<int> innerList = new List<int>();
    for (int j = 0; j< array.GetLength(1); j++)
    {
        innerList.Add(array[i, j]);
    }
    list.Add(innerList);
}
  1. 列表轉換為二維數組:
List<List<int>> list = new List<List<int>>()
{
    new List<int> { 1, 2 },
    new List<int> { 3, 4 },
    new List<int> { 5, 6 }
};

int[,] array = new int[list.Count, list[0].Count];

for (int i = 0; i< list.Count; i++)
{
    for (int j = 0; j< list[i].Count; j++)
    {
        array[i, j] = list[i][j];
    }
}
  1. 二維數組轉換為字典(Dictionary):
int[,] array = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
Dictionary<int, int> dictionary = new Dictionary<int, int>();

for (int i = 0; i< array.GetLength(0); i++)
{
    for (int j = 0; j< array.GetLength(1); j++)
    {
        dictionary[i * array.GetLength(1) + j] = array[i, j];
    }
}
  1. 字典轉換為二維數組:
Dictionary<int, int> dictionary = new Dictionary<int, int>()
{
    { 0, 1 },
    { 1, 2 },
    { 2, 3 },
    { 3, 4 },
    { 4, 5 },
    { 5, 6 }
};

int rows = (int)Math.Sqrt(dictionary.Count);
int cols = dictionary.Count / rows;
int[,] array = new int[rows, cols];

for (int i = 0; i< rows; i++)
{
    for (int j = 0; j< cols; j++)
    {
        array[i, j] = dictionary[i * cols + j];
    }
}

這些示例展示了如何在C#中將二維數組與其他數據結構進行轉換。請根據實際需求調整代碼。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女