- Csharp how to make an array of arrays
- C# Creating an array of arrays
- 16: Multidimensional Arrays in C#
- Array of Arrays
- Initialize array of arrays with a set array length
- How to convert List<List<int>> to an array of arrays
- Массивы массивов (Руководство по программированию на C#)
- Пример
- См. также
- Многомерные массивы (Руководство по программированию на C#)
- Инициализация массива
- См. также
- C# Jagged Arrays: An Array of Array
Csharp how to make an array of arrays
Solution 1: Simple example of array of arrays or multidimensional array is as follows: To test the array: Solution 2: you need a jagged array, that is the best solution here Converting the arrays in your declarations to jagged arrays should make it work.
C# Creating an array of arrays
What you need to do is this:
int[] list1 = new int[4] < 1, 2, 3, 4>; int[] list2 = new int[4] < 5, 6, 7, 8>; int[] list3 = new int[4] < 1, 3, 2, 1 >; int[] list4 = new int[4] < 5, 4, 3, 2 >; int[][] lists = new int[][] < list1 , list2 , list3 , list4 >;
Another alternative would be to create a List
The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.
int[] list1 = new int[4] < 1, 2, 3, 4>; int[] list2 = new int[4] < 5, 6, 7, 8>; int[] list3 = new int[4] < 1, 3, 2, 1 >; int[] list4 = new int[4] < 5, 4, 3, 2 >; int[,] lists = new int[4,4] < , , etc. >;
I think you may be looking for Jagged Arrays, which are different from multi-dimensional arrays (as you are using in your example) in C#. Converting the arrays in your declarations to jagged arrays should make it work. However, you’ll still need to use two loops to iterate over all the items in the 2D jagged array.
C# Arrays (With Examples), In C#, we can initialize an array during the declaration. For example, int [] numbers = <1, 2, 3, 4, 5>;.1,>
16: Multidimensional Arrays in C#
In this C# tutorial I will teach about loops in C#. Loops are used to spit out data multiple times Duration: 9:58
Array of Arrays
Simple example of array of arrays or multidimensional array is as follows:
int[] a1 = < 1, 2, 3 >; int[] a2 = < 4, 5, 6 >; int[] a3 = < 7, 8, 9, 10, 11 >; int[] a4 = < 50, 58, 90, 91 >; int[][] arr = ;
you need a jagged array, that is the best solution here
string[][] jaggedArray = new string[3][]; jaggedArray[0] = new string[5]; jaggedArray[1] = new string[4]; jaggedArray[2] = new string[2]
jaggedArray[0][3] = "An Apple" jaggedArray[2][1] = "A Banana"
Before you can use jaggedArray, its elements must be initialized.
in your case you could wrap the array in another class but that seems highly redundant imho
You can use List of List. List — it is just dynamic array:
var list = new List>(); list.Add(new List()); list[0].Add(1); Console.WriteLine(list[0][0]);
Array Class (System), Unlike the classes in the System.Collections namespaces, Array has a fixed capacity. To increase the capacity, you must create a new Array object with the
Initialize array of arrays with a set array length
It seems like you are trying to find a way to initialize Jagged array in c#: please refer to the following example:
int[][] jaggedArray2 = new int[][] < new int[] , new int[] , new int[] >;
The short form for the same sample is shown below:
int[][] jaggedArray2 = < new int[] , new int[] , new int[] >;
You can also perform the initialization in several steps:
int[][] jaggedArray = new int[3][]; jaggedArray[0] = new int[5]; jaggedArray[1] = new int[4]; jaggedArray[2] = new int[2]; jaggedArray[0] = new int[] < 1, 3, 5, 7, 9 >; jaggedArray[1] = new int[] < 0, 2, 4, 6 >; jaggedArray[2] = new int[] < 11, 22 >;
And, apparently, you can implement a sort of for or foreach loop in order to populate the array from some data structure. More reading available at: http://msdn.microsoft.com/en-us/library/2s05feca.aspx
Also, you should probably consider a use of multidimensional array, like int[,] (the C# syntax in this case is different from Java lang). Hope this will help.
There is no syntax you are looking for.
One statement option could be
int[][] arrPos = Enumerable.Range(0, length).Select(_ => new int[length]).ToArray();
C# | Jagged Arrays, Jagged array is a array of arrays such that member arrays can be of different sizes. In other words, the length of each array index can differ.
How to convert List<List<int>> to an array of arrays
int[][] arrays = lst.Select(a => a.ToArray()).ToArray();
lst.Select(l => l.ToArray()).ToArray()
If you really wanted two-dimentional array ( int[,] , not int[][] ), that would be more difficult and the best solution would probably be using nested for s.
you can easily do it using linq.
int[][] arrays = lst.Select(a => a.ToArray()).ToArray();
but if you want another way you can loop through the list and manually generate the 2d array.
how to loop through nested list
Passing arrays as arguments in C#, One can pass the 1-D arrays to a method. There are various options like first, you declare and initialize the array separately then pass it to
Массивы массивов (Руководство по программированию на C#)
Массив массивов — это массив, элементы которого являются массивами и могут быть различных размеров. Массив с массивом иногда называют «массивом массивов». В следующих примерах показано, как объявлять, инициализировать массивы и обращаться к ней.
Ниже объявляется одномерный массив из трех элементов, каждый из которых является одномерным массивом целых чисел:
int[][] jaggedArray = new int[3][];
Прежде чем использовать jaggedArray , его элементы необходимо инициализировать. Это можно сделать следующим образом:
jaggedArray[0] = new int[5]; jaggedArray[1] = new int[4]; jaggedArray[2] = new int[2];
Каждый элемент представляет собой одномерный массив целых чисел. Первый из них содержит 5 целых чисел, второй — 4, а третий — 2.
Кроме того, с помощью инициализаторов можно заполнять элементы массива значениями (при этом вам не потребуется знать размер массива). Пример:
jaggedArray[0] = new int[] < 1, 3, 5, 7, 9 >; jaggedArray[1] = new int[] < 0, 2, 4, 6 >; jaggedArray[2] = new int[] < 11, 22 >;
Также массив можно инициализировать при объявлении, как показано ниже:
int[][] jaggedArray2 = new int[][] < new int[] < 1, 3, 5, 7, 9 >, new int[] < 0, 2, 4, 6 >, new int[] < 11, 22 >>;
Можно использовать следующую краткую форму. Обратите внимание, что при инициализации элементов нельзя опускать оператор new , поскольку механизм инициализации по умолчанию для них не предусмотрен:
int[][] jaggedArray3 = < new int[] < 1, 3, 5, 7, 9 >, new int[] < 0, 2, 4, 6 >, new int[] < 11, 22 >>;
В массиве массивов элементы являются ссылочными типами и инициализируются значением null .
Доступ к отдельным элементам массива можно получить способами, показанными в следующих примерах:
// Assign 77 to the second element ([1]) of the first array ([0]): jaggedArray3[0][1] = 77; // Assign 88 to the second element ([1]) of the third array ([2]): jaggedArray3[2][1] = 88;
Массивы массивов и многомерные массивы можно смешивать. Ниже показаны объявление и инициализация одномерного массива массивов, элементами которого являются двухмерные массивы разного размера. Дополнительные сведения см. в разделе Многомерные массивы.
int[][,] jaggedArray4 = new int[3][,] < new int[,] < , >, new int[,] < , , >, new int[,] < , , > >;
В этом примере демонстрируется доступ к отдельным элементам, для чего отображается значение элемента [1,0] первого массива ( 5 ):
System.Console.Write("", jaggedArray4[0][1, 0]);
Метод Length возвращает число массивов, содержащихся в массиве массивов. Допустим, предыдущий массив был объявлен с использованием следующей строки:
System.Console.WriteLine(jaggedArray4.Length);
Пример
В этом примере создается массив, элементы которого являются массивами. Все элементы массива имеют разный размер.
class ArrayTest < static void Main() < // Declare the array of two elements. int[][] arr = new int[2][]; // Initialize the elements. arr[0] = new int[5] < 1, 3, 5, 7, 9 >; arr[1] = new int[4] < 2, 4, 6, 8 >; // Display the array elements. for (int i = 0; i < arr.Length; i++) < System.Console.Write("Element(): ", i); for (int j = 0; j < arr[i].Length; j++) < System.Console.Write("", arr[i][j], j == (arr[i].Length - 1) ? "" : " "); > System.Console.WriteLine(); > // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); > > /* Output: Element(0): 1 3 5 7 9 Element(1): 2 4 6 8 */
См. также
Многомерные массивы (Руководство по программированию на C#)
Массивы могут иметь несколько измерений. Например, следующее объявление создает двухмерный массив из четырех строк и двух столбцов.
Следующее объявление создает массив из трех измерений: 4, 2 и 3.
Инициализация массива
Массив можно инициализировать при объявлении, как показано в следующем примере.
// Two-dimensional array. int[,] array2D = new int[,] < < 1, 2 >, < 3, 4 >, < 5, 6 >, < 7, 8 >>; // The same array with dimensions specified. int[,] array2Da = new int[4, 2] < < 1, 2 >, < 3, 4 >, < 5, 6 >, < 7, 8 >>; // A similar array with string elements. string[,] array2Db = new string[3, 2] < < "one", "two" >, < "three", "four" >, < "five", "six" >>; // Three-dimensional array. int[,,] array3D = new int[,,] < < < 1, 2, 3 >, < 4, 5, 6 >>, < < 7, 8, 9 >, < 10, 11, 12 >> >; // The same array with dimensions specified. int[,,] array3Da = new int[2, 2, 3] < < < 1, 2, 3 >, < 4, 5, 6 >>, < < 7, 8, 9 >, < 10, 11, 12 >> >; // Accessing array elements. System.Console.WriteLine(array2D[0, 0]); System.Console.WriteLine(array2D[0, 1]); System.Console.WriteLine(array2D[1, 0]); System.Console.WriteLine(array2D[1, 1]); System.Console.WriteLine(array2D[3, 0]); System.Console.WriteLine(array2Db[1, 0]); System.Console.WriteLine(array3Da[1, 0, 1]); System.Console.WriteLine(array3D[1, 1, 2]); // Getting the total count of elements or the length of a given dimension. var allLength = array3D.Length; var total = 1; for (int i = 0; i < array3D.Rank; i++) < total *= array3D.GetLength(i); >System.Console.WriteLine(" equals ", allLength, total); // Output: // 1 // 2 // 3 // 4 // 7 // three // 8 // 12 // 12 equals 12
Можно также инициализировать массив без указания ранга.
Чтобы объявить переменную массива без инициализации, используйте оператор new для присвоения массива переменной. Использование оператора new показано в следующем примере.
int[,] array5; array5 = new int[,] < < 1, 2 >, < 3, 4 >, < 5, 6 >, < 7, 8 >>; // OK //array5 = , , , >; // Error
В следующем примере присваивается значение конкретному элементу массива.
Аналогичным образом, в следующем примере получается значение конкретного элемента массива, которое присваивается переменной elementValue .
int elementValue = array5[2, 1];
В следующем примере кода элементы массива инициализируются с использованием значений по умолчанию (кроме массивов массивов).
См. также
C# Jagged Arrays: An Array of Array
A jagged array is an array of array. Jagged arrays store arrays instead of literal values.
A jagged array is initialized with two square brackets [][]. The first bracket specifies the size of an array, and the second bracket specifies the dimensions of the array which is going to be stored.
The following example declares jagged arrays.
int[][] jArray1 = new int[2][]; // can include two single-dimensional arrays int[][,] jArray2 = new int[3][,]; // can include three two-dimensional arrays
In the above example, jArray1 can store up to two single-dimensional arrays. jArray2 can store up to three two-dimensional, arrays [,] specifies the two-dimensional array.
int[][] jArray = new int[2][]; jArray[0] = new int[3]; jArray[1] = new int[4];
You can also initialize a jagged array upon declaration like the below.
int[][] jArray = new int[2][]< new int[3], new int[4] >; jArray[0][0]; //returns 1 jArray[0][1]; //returns 2 jArray[0][2]; //returns 3 jArray[1][0]; //returns 4 jArray[1][1]; //returns 5 jArray[1][2]; //returns 6 jArray[1][3]; //returns 7
You can access a jagged array using two for loops, as shown below.
int[][] jArray = new int[2][]< new int[3], new int[4] >; for(int i=0; ifor(int j=0; j
The following jagged array stores two-dimensional arrays where the second bracket [,] indicates the two-dimensional array.
int[][,] jArray = new int[2][,]; jArray[0] = new int[3, 2] < < 1, 2 >, < 3, 4 >, < 5, 6 >>; jArray[1] = new int[2, 2] < < 7, 8 >, < 9, 10 >>; jArray[0][1, 1]; //returns 4 jArray[1][1, 0]; //returns 9 jArray[1][1, 1]; //returns 10
If you add one more bracket then it will be array of array of arry.
int[][][] intJaggedArray = new int[2][][] < new int[2][] < new int[3] < 1, 2, 3>, new int[2] < 4, 5>>, new int[1][] < new int[3] < 7, 8, 9>> >; Console.WriteLine(intJaggedArray[0][0][0]); // 1 Console.WriteLine(intJaggedArray[0][1][1]); // 5 Console.WriteLine(intJaggedArray[1][0][2]); // 9
In the above example of a jagged array, three brackets [][][] means an array of array of array. So, intJaggedArray will contain two elements, which means two arrays. Now, each of these arrays also contains an array (single-dimension). intJaggedArray[0][0][0] points to the first element of first inner array. intJaggedArray[1][0][2] points to the third element of the second inner array. The following figure illustrates this.