Многомерный массив си шарп

Многомерные массивы (Руководство по программированию на 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]; 

В следующем примере кода элементы массива инициализируются с использованием значений по умолчанию (кроме массивов массивов).

См. также

Источник

Многомерный массив си шарп

Массив представляет набор однотипных данных. Объявление массива похоже на объявление переменной за тем исключением, что после указания типа ставятся квадратные скобки:

тип_переменной[] название_массива;

Например, определим массив целых чисел:

После определения переменной массива мы можем присвоить ей определенное значение:

Здесь вначале мы объявили массив nums, который будет хранить данные типа int . Далее используя операцию new , мы выделили память для 4 элементов массива: new int[4] . Число 4 еще называется длиной массива . При таком определении все элементы получают значение по умолчанию, которое предусмотренно для их типа. Для типа int значение по умолчанию — 0.

Также мы сразу можем указать значения для этих элементов:

int[] nums2 = new int[4] < 1, 2, 3, 5 >; int[] nums3 = new int[] < 1, 2, 3, 5 >; int[] nums4 = new[] < 1, 2, 3, 5 >; int[] nums5 = < 1, 2, 3, 5 >;

Все перечисленные выше способы будут равноценны.

Подобным образом можно определять массивы и других типов, например, массив значений типа string :

Индексы и получение элементов массива

Для обращения к элементам массива используются индексы . Индекс представляет номер элемента в массиве, при этом нумерация начинается с нуля, поэтому индекс первого элемента будет равен 0, индекс четвертого элемента — 3.

Используя индексы, мы можем получить элементы массива:

int[] numbers = < 1, 2, 3, 5 >; // получение элемента массива Console.WriteLine(numbers[3]); // 5 // получение элемента массива в переменную var n = numbers[1]; // 2 Console.WriteLine(n); // 2

Также мы можем изменить элемент массива по индексу:

int[] numbers = < 1, 2, 3, 5 >; // изменим второй элемент массива numbers[1] = 505; Console.WriteLine(numbers[1]); // 505

И так как у нас массив определен только для 4 элементов, то мы не можем обратиться, например, к шестому элементу. Если мы так попытаемся сделать, то мы получим ошибку во время выполнения:

int[] numbers = < 1, 2, 3, 5 >; Console.WriteLine(numbers[6]); // ! Ошибка - в массиве только 4 элемента

Свойство Length и длина массива

каждый массив имеет свойство Length , которое хранит длину массива. Например, получим длину выше созданного массива numbers:

int[] numbers = < 1, 2, 3, 5 >; Console.WriteLine(numbers.Length); // 4

Для получения длины массива после названия массива через точку указывается свойство Length : numbers.Length .

Получение элементов с конца массива

Благодаря наличию свойства Length , мы можем вычислить индекс последнего элемента массива — это длина массива — 1. Например, если длина массива — 4 (то есть массив имеет 4 элемента), то индекс последнего элемента будет равен 3. И, используя свойство Length , мы можем легко получить элементы с конца массива:

int[] numbers = < 1, 2, 3, 5>; Console.WriteLine(numbers[numbers.Length - 1]); // 5 - первый с конца или последний элемент Console.WriteLine(numbers[numbers.Length - 2]); // 3 - второй с конца или предпоследний элемент Console.WriteLine(numbers[numbers.Length - 3]); // 2 - третий элемент с конца

Однако при подобном подходе выражения типа numbers.Length — 1 , смысл которых состоит в том, чтобы получить какой-то определенный элемент с конца массива, утяжеляют код. И, начиная, с версии C# 8.0 в язык был добавлен специальный оператор ^ , с помощью которого можно задать индекс относительно конца коллекции.

Перепишем предыдущий пример, применяя оператор ^ :

int[] numbers = < 1, 2, 3, 5>; Console.WriteLine(numbers[^1]); // 5 - первый с конца или последний элемент Console.WriteLine(numbers[^2]); // 3 - второй с конца или предпоследний элемент Console.WriteLine(numbers[^3]); // 2 - третий элемент с конца

Перебор массивов

Для перебора массивов мы можем использовать различные типы циклов. Например, цикл foreach :

int[] numbers = < 1, 2, 3, 4, 5 >; foreach (int i in numbers)

Здесь в качестве контейнера выступает массив данных типа int . Поэтому мы объявляем переменную с типом int

Подобные действия мы можем сделать и с помощью цикл for:

int[] numbers = < 1, 2, 3, 4, 5 >; for (int i = 0; i

В то же время цикл for более гибкий по сравнению с foreach . Если foreach последовательно извлекает элементы контейнера и только для чтения, то в цикле for мы можем перескакивать на несколько элементов вперед в зависимости от приращения счетчика, а также можем изменять элементы:

int[] numbers = < 1, 2, 3, 4, 5 >; for (int i = 0; i

Также можно использовать и другие виды циклов, например, while :

int[] numbers = < 1, 2, 3, 4, 5 >; int i = 0; while(i

Многомерные массивы

Массивы характеризуются таким понятием как ранг или количество измерений. Выше мы рассматривали массивы, которые имеют одно измерение (то есть их ранг равен 1) — такие массивы можно представлять в виде ряда (строки или столбца) элемента. Но массивы также бывают многомерными. У таких массивов количество измерений (то есть ранг) больше 1.

Массивы которые имеют два измерения (ранг равен 2) называют двухмерными. Например, создадим одномерный и двухмерный массивы, которые имеют одинаковые элементы:

int[] nums1 = new int[] < 0, 1, 2, 3, 4, 5 >; int[,] nums2 = < < 0, 1, 2 >, < 3, 4, 5 >>;

Визуально оба массива можно представить следующим образом:

Источник

Arrays (C# Programming Guide)

You can store multiple variables of the same type in an array data structure. You declare an array by specifying the type of its elements. If you want the array to store elements of any type, you can specify object as its type. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object.

Example

The following example creates single-dimensional, multidimensional, and jagged arrays:

class TestArraysClass < static void Main() < // Declare a single-dimensional array of 5 integers. int[] array1 = new int[5]; // Declare and set array element values. int[] array2 = new int[] < 1, 3, 5, 7, 9 >; // Alternative syntax. int[] array3 = < 1, 2, 3, 4, 5, 6 >; // Declare a two dimensional array. int[,] multiDimensionalArray1 = new int[2, 3]; // Declare and set array element values. int[,] multiDimensionalArray2 = < < 1, 2, 3 >, < 4, 5, 6 >>; // Declare a jagged array. int[][] jaggedArray = new int[6][]; // Set the values of the first array in the jagged array structure. jaggedArray[0] = new int[4] < 1, 2, 3, 4 >; > > 

Array overview

An array has the following properties:

  • An array can be single-dimensional, multidimensional or jagged.
  • The number of dimensions and the length of each dimension are established when the array instance is created. These values can’t be changed during the lifetime of the instance.
  • The default values of numeric array elements are set to zero, and reference elements are set to null .
  • A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null .
  • Arrays are zero indexed: an array with n elements is indexed from 0 to n-1 .
  • Array elements can be of any type, including an array type.
  • Array types are reference types derived from the abstract base type Array. All arrays implement IList, and IEnumerable. You can use the foreach statement to iterate through an array. Single-dimensional arrays also implement IList and IEnumerable .

Default value behaviour

  • For value types, the array elements are initialized with the default value, the 0-bit pattern; the elements will have the value 0 .
  • All the reference types (including the non-nullable), have the values null .
  • For nullable value types, HasValue is set to false and the elements would be set to null .

Arrays as Objects

In C#, arrays are actually objects, and not just addressable regions of contiguous memory as in C and C++. Array is the abstract base type of all array types. You can use the properties and other class members that Array has. An example of this is using the Length property to get the length of an array. The following code assigns the length of the numbers array, which is 5 , to a variable called lengthOfNumbers :

int[] numbers = < 1, 2, 3, 4, 5 >; int lengthOfNumbers = numbers.Length; 

The Array class provides many other useful methods and properties for sorting, searching, and copying arrays. The following example uses the Rank property to display the number of dimensions of an array.

class TestArraysClass < static void Main() < // Declare and initialize an array. int[,] theArray = new int[5, 10]; System.Console.WriteLine("The array has dimensions.", theArray.Rank); > > // Output: The array has 2 dimensions. 

See also

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

Источник

Multidimensional Arrays (C# Programming Guide)

Arrays can have more than one dimension. For example, the following declaration creates a two-dimensional array of four rows and two columns.

The following declaration creates an array of three dimensions, 4, 2, and 3.

Array Initialization

You can initialize the array upon declaration, as is shown in the following example.

// 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 

You can also initialize the array without specifying the rank.

If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the variable. The use of new is shown in the following example.

int[,] array5; array5 = new int[,] < < 1, 2 >, < 3, 4 >, < 5, 6 >, < 7, 8 >>; // OK //array5 = , , , >; // Error 

The following example assigns a value to a particular array element.

Similarly, the following example gets the value of a particular array element and assigns it to variable elementValue .

int elementValue = array5[2, 1]; 

The following code example initializes the array elements to default values (except for jagged arrays).

See also

Источник

Оцените статью