C#数组维度转换:一维数组&二维数组&三维数组相互转换
最近项目需要用到数组维度转换,网上资源较少,写一个分享与备用
1.一维数组转二维数组
/// <summary> /// 一维数组转2维数组(矩阵) /// </summary> /// <param name="obj"></param> /// <param name="len">矩阵行数</param> /// <returns></returns> public static T[,] OneD_2<T>(T[] obj,int len) { if (obj.Length % len != 0) return null; int width = obj.Length / len; T[,] obj2 = new T[len, width]; for (int i = 0; i < obj.Length; i++) { obj2[i / width, i % width] = obj[i]; } return obj2; }
2.一维数组转三维数组
/// <summary> /// 一维数组转3维数组 /// </summary> /// <param name="obj"></param> /// <param name="len">一维长</param> /// <param name="wid">二维长</param> /// <returns></returns> public static T[,,] OneD_3<T>(T[] obj,int len,int wid) { if (obj.Length % (len* wid) != 0) return null; int height = obj.Length / (len * wid); T[,,] obj2 = new T[len, wid, height]; for (int i = 0; i < obj.Length; i++) { //核心思想把握每个维度的值多久变一次与设置最大值,变化频率设置用除法,设置最大值用求余 //第二及之后的维度最大值为自身维度最大值 -1(意思就是最后需要对自身维度最大值求余) obj2[i / (wid* height), (i / height) % wid, i % height] = obj[i]; } return obj2; }
3.二维数组转一维数组
/// <summary> /// 二维数组转一维数组 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static T[] TwoD_1<T>(T[,] obj) { T[] obj2 = new T[obj.Length]; for (int i = 0; i < obj.Length; i++) obj2[i] = obj[i / obj.GetLength(1), i % obj.GetLength(1)]; return obj2; }
4.三维数组转一维数组
/// <summary> /// 三维数组转一维数组 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static T[] ThreeD_1<T>(T[,,] obj) { T[] obj2 = new T[obj.Length]; int wid = obj.GetLength(1);//GetLength从0开始 int height = obj.GetLength(2); for (int i = 0; i < obj.Length; i++) obj2[i] = obj[i / (wid * height), (i / height) % wid, i % height]; return obj2; }