1. Basic concepts of one-dimensional arrays
It has a continuous memory space and stores a group of data of the same type. The length of the array cannot be changed. The subscript of the array starts from 0 .
2. Basic use of arrays
int[] arr;//声明
arr = new int[4] {
1, 2, 3, 4};//赋值并且初始化
string[] str;
str = new string[4] {
"aa", "bb", "cc", "dd" };
The first is to define the array type, int, float, string, char, object, etc., and then perform assignment and initialization, that is, give the array a length and initialize the elements in it. You can also use the shorthand method of defining an array
int[] arr = {
1, 2, 3, 4 };//简写
There is no need to initialize when assigning, as follows:
int[] arr;
arr = new int[4];
If it is an int type, all elements will be initialized to 0 by default at this time , and if it is a string type, it will default to an empty string.
3. Access the array
(1) Access array elements
int[] arr = {
1, 2, 3, 4 };
Console.WriteLine(arr[0]);//访问下标为0的数组元素
(2) Get the length of the array
int a = arr.Length;//调用数组的Length属性,即可获取到数组的长度
Console.WriteLine(a);
(3) Traverse the array
The most commonly used for loop convenience array
int[] arr = {
1, 2, 3, 4 };
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
4. Two-dimensional array
int[,] arr = new int[3, 3]{
{
1, 2, 3 },
{
4, 5, 6 },
{
7, 8, 9 }
};
Two-dimensional arrays and one-dimensional arrays are defined in similar ways, except that traversing two-dimensional arrays is a bit more troublesome. You need to use a method GetLength() . Pass in parameter 0 to get the number of rows in the two-dimensional array, and pass in parameter 1 to get two. Number of columns in the dimensional array
arr.GetLength(0);//获取行数,3
arr.GetLength(1);//获取列数,3
Then you can traverse the two-dimensional array
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.WriteLine(arr[i, j]);
}
}
5. Jagged array
That is, each element of the outer array is an array
int[][] arr = new int[2][];//交错数组
arr[0] = new int[3] {
1, 2, 3 };
arr[1] = new int[4] {
4, 5, 6, 7 };
Somewhat similar to a two-dimensional array