Convert from list <double []> to double [,]
Is there a single line (without loops) that converts List<double[]> to double[,] ?
Converting to double[,] possible only by cycling through the list and requires that all arrays contained in the list have the same size:
double[,] arr = new double[list.Count, list[0].Length]; for (int i = 0; i < list.Count; i++) { for (int j = 0; j < list[0].Length; j++) { arr[i, j] = list[i][j]; } } Of course, you can easily create an array of arrays with double[][] arrays by calling .ToArray() :
double[] array = new double[] { 1.0, 2.0, 3.0 }; double[] array1 = new double[] { 4.0, 5.0, 6.0 }; List<double[]> list = new List<double[]>(); list.Add(array); list.Add(array1); double[][] jaggedArray = list.ToArray(); Well, you probably wonโt be able to implement it without loops, but you can make use one-line:
double[,] array = list.To2DArray(); To2DArray is an extension method implemented as follows:
public static class ExtensionMethods { public static T[,] To2DArray<T>(this IEnumerable<IEnumerable<T>> source) { var jaggedArray = source.Select(r => r.ToArray()).ToArray(); int rows = jaggedArray.GetLength(0); int columns = jaggedArray.Max(r => r.Length); var array = new T[rows, columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < jaggedArray[i].Length; j++) { array[i, j] = jaggedArray[i][j]; } } return array; } } Please note that it will only work in C # 4, as earlier versions do not support covariance. This option should work in C # 3, but it is more specific:
public static T[,] To2DArray<T>(this IEnumerable<T[]> source) { var jaggedArray = source.ToArray(); // same code from here } If a 2-dimensional array is to be created from the list of 1 dim-arrays, then a loop is required, although it may not look like the one on the call site.
public static T[,] ToMultidimensional<T>(this T[][] arr, int maxSize) { T[,] md = (T[,])Array.CreateInstance(typeof(double), arr.Length, maxSize); for (int i = 0; i < arr.Length; i++) for (int j = 0; j < arr[i].Length; j++) md[i, j] = arr[i][j]; return md; } var arr = new List<double[]> { new double[] { 1, 2, 3 }, new double[] { 4, 5 } } .ToArray(); var j = arr.ToMultidimensional(arr.Max(a => a.Length)); This syntax should work: return new List {new double [] {minX, minY}, new double [] {maxX, maxY}};
Here is the right decision if I take your approach. Demo
public class Program { public static void Main() { double[,] disQC = new double[5, 5]; List<List<double>> lQC = new List<List<double>>(); for (int j = 0; j < 5; j++) { lQC.Add(new List<double>()); for (int i = 0; i < 5; i++) { if (i % 2 == 0){ disQC[i, j] =i + 1 ; } else{ disQC[i, j] = j + 1; } lQC[j].Add(disQC[i, j]); } } lQC.ForEach(l => { l.ForEach(t => Console.Write(t)); Console.WriteLine(""); }); } }