Answer the question
In order to leave comments, you need to log in
How can a List of one-dimensional arrays be written to a two-dimensional array?
Hello.
Some List for one-dimensional string arrays is declared:
Next, let's create an arbitrary number of one-dimensional string arrays of different sizes:List<string[]> arrList = new List<string[]>();
string[] arrOfStr1 = new string[10] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
string[] arrOfStr2 = new string[8] { "a", "b", "c", "d", "e", "f", "g", "h" };
string[] arrOfStr3 = new string[9] { "a", "b", "c", "d", "e", "f", "g", "h", "i" };
arrList.Add(arrOfStr1);
arrList.Add(arrOfStr2);
arrList.Add(arrOfStr3);
arrOfStr1, arrOfStr2, arrOfStr3
) would be a column of the future two-dimensional array. arrList.Count;
arrOfStr1, arrOfStr2, arrOfStr3
) in the following way:int[] biggestNumbers = new int[arrList.Count];
for (int i = 0; i < arrList.Count; i++)
biggestNumbers[i] = arrList[i].Length;
biggestNumbers.Max();
string[,] dataArr = new string[biggestNumbers.Max(), arrList.Count];
Answer the question
In order to leave comments, you need to log in
string[,] dataArr = CreateRectangularArray(arrList);
static T[,] CreateRectangularArray<T>(IList<T[]> arrays)
{
if (arrays.Count == 0)
{
Console.WriteLine("Лист одномерных массивов arrays пуст (nullable). Из-за этого метод CreateRectangularArray не будет работать.");
int minorLength = 5;
T[,] ret = new T[arrays.Count, minorLength];
return ret;
}
else
{
int minorLength = arrays[0].Length;
T[,] ret = new T[arrays.Count, minorLength];
for (int i = 0; i < arrays.Count; i++)
{
var array = arrays[i];
if (array.Length != minorLength)
{
throw new ArgumentException("All arrays must be the same length");
}
for (int j = 0; j < minorLength; j++)
{
ret[i, j] = array[j];
}
}
return ret;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question