C#中二维数组与其他数据结构的转换

   2024-09-30 2700
核心提示:在C#中,二维数组可以与其他数据结构(如列表、字典等)进行转换二维数组转换为列表(List):int[,] array = new int[,] { { 1,

在C#中,二维数组可以与其他数据结构(如列表、字典等)进行转换

二维数组转换为列表(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);}
列表转换为二维数组:
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];    }}
二维数组转换为字典(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];    }}
字典转换为二维数组:
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#中将二维数组与其他数据结构进行转换。请根据实际需求调整代码。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号