飞道的博客

C# 一维数组与二维数组相互转换

434人阅读  评论(0)

  本文就这么朴实无华且枯燥地向大家分享C#中: 一维数组二维数组 的相互转换(一维→二维;二维→一维)……希望能帮到有需求的小伙伴(*^▽^*)。全文完整代码(直接复制运行)如下:

using System;

namespace testCodes0411
{
   
    class Program
    {
   
        static void Main(string[] args)
        {
   
            double[] a = {
    1, 2, 3, 4, 5, 6 };
            double[,] b = Row2VecD(a);
            double[,] c = Row2ArrT(a, 2);
            //double[,] c = RowToArrD(a, 2);
            double[] d = Arr2RowD(c);

            Console.WriteLine("\n行向量→列向量");
            for(int i = 0; i < b.GetLength(0); i++)
            {
   
                for(int j = 0; j < b.GetLength(1); j++)
                {
   
                    Console.WriteLine("b[{0},{1}]:{2}", i, j, b[i, j]);
                }
            }

            Console.WriteLine("\n\n行向量→数组");
            for (int i = 0; i < c.GetLength(0); i++)
            {
   
                for (int j = 0; j < c.GetLength(1); j++)
                {
   
                    Console.WriteLine("c[{0},{1}]:{2}", i, j, c[i, j]);
                }
            }

            Console.WriteLine("\n\n数组→行向量");
            for (int i = 0; i < d.Length; i++)
            {
   
                Console.WriteLine("d[{0}]:{1}", i, d[i]);
            }

            Console.ReadKey();
        }

        //行向量→数组(内存复制版)
        static double[,] RowToArrD(double[]src,int row)
        {
   
            if (src.Length % row != 0) return null;
            int col = src.Length / row;
            double[,] dst = new double[row, col];
            for(int i = 0; i < row; i++)
            {
   
                //说明:“二维数组”【顺序储存】<=>“一维数组”
                Buffer.BlockCopy(src, i * col * sizeof(double),
                    dst, i * col * sizeof(double), col * sizeof(double));
            }
            return dst;
        }

        //行向量→列向量(内存复制版)
        static double[,] Row2VecD(double[] src)
        {
   
            double[,] dst = new double[src.Length, 1];
            Buffer.BlockCopy(src, 0, dst, 0, sizeof(double) * src.Length);
            return dst;
        }

        //行向量→数组(循环版;泛型版)
        static T[,] Row2ArrT<T>(T[] vec, int row)
        {
   
            if (vec.Length % row != 0) return null;
            int col = vec.Length / row;
            T[,] ret = new T[row, col];
            for (int i = 0; i < vec.Length; i++)
            {
   
                ret[i / col, i % col] = vec[i];
            }
            return ret;
        }
        
        //数组→行向量(内存复制版)
        static double[] Arr2RowD(double[,] src)
        {
   
            int elem = src.GetLength(0) * src.GetLength(1);
            double[] dst = new double[elem];
            Buffer.BlockCopy(src, 0, dst, 0, elem * sizeof(double));
            return dst;
        }
    }
}

  友情提示:若顾及效率,最好使用 内存复制版 函数

参考博文:

  1. C#中,一维数组如何合并成二维数组?除循环赋值有无其他方法?
  2. C#数据结构-Array.Copy和Buffer.BlockCopy详解.

转载:https://blog.csdn.net/C_xxy/article/details/115714066
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场