C# Array Basics

1. Introduction

An array is a fixed-size sequential collection that stores elements of the same type. An array is a collection used to store data, and an array is generally considered to be a collection of variables of the same type. A specific element in the array is accessed by index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element, and the highest address corresponds to the last element.

2. Array syntax

2.1 Declaring arrays

When C# declares an array, square brackets [] must follow the type, not the identifier. Example:

// datatype数据类型 
// []数组的秩(维度) 
// arrayName数组变量名
datatype[] arrayName;

2.2 Initialize the array

Declaring an array does not initialize the array in memory. When an array variable is initialized, it can be assigned to the array. An array is a reference type, so you need to use the new keyword to create an instance of an array.

int[] arr1 = new int[5]; // 创建了length为5的数组,数组项都为0
int[] arr2 = new int[5] {1,2,3,4,5}; // 创建了length为5的数组,并初始化数组
int[] arr3 = new int[] {1,2,3,4,5}; // 初始化时也可不写数组长度

2.3 Assigning and accessing arrays

Assignment: You can assign a value to a single array element by using the index number;

Access: Elements are accessed by indexed array name. This is done by placing the index of the element in square brackets after the array name.

int[] arr = new int[2] {1,2};
arr[0] = 2; // 赋值
Console.WriteLine(arr[0]); // 2   访问
arr[2] = 5;  // 报错,不能修改数组外的值
Console.WriteLine(arr[2]); // 报错。不能访问数组不存在的值

Note: You can modify the value in the array through subscript access, but if you cannot access the value of the array subscript exceeding the limit, an error will be reported.

3. Array traversal

The C# loop methods sorted out before, such as for, while, forEach, etc., can be used to traverse the array; here we will not give examples one by one, but focus on foreach:

int[] arr = new int[] { 1, 2, 3, 4 };
foreach (int element in arr)
{
    // element代表这数组每项的值
	Console.WriteLine(element);
}

Fourth, the properties and methods of arrays

4.1 Properties

Attributes describe
IsFixedSize Gets a value indicating whether the Array has a fixed size.
IsReadOnly Gets a value indicating whether the Array is read-only.
IsSynchronized Gets a value indicating whether access to the Array is synchronized (thread-safe).
Length Get the total number of elements in all dimensions of the Array .
LongLength Gets a 64-bit integer representing the total number of elements in all dimensions of the Array .
MaxLength Gets the maximum number of elements that may be contained in the array.
Rank Get the rank (dimension) of Array . For example, a one-dimensional array returns 1, a two-dimensional array returns 2, and so on.
SyncRoot Get an object that can be used to synchronize access to the Array .

4.2 Method

method describe
Clear(Array) Clear the contents of the array.
Clone() Create a shallow copy of Array .
Copy(Array, Array, Int32) Copy a range of elements in an Array starting from the first element , and paste them into another Array (starting from the first element). The length is specified as a 32-bit integer.
Empty() Returns an empty array.
[FindIndex(T], Int32, Predicate) Searches for elements that match the conditions defined by the specified predicate and returns the zero-based index of the first occurrence within the range of elements in Array from the specified index to the last element.
[FindLast(T], Predicate) Searches for elements that match the conditions defined by the specified predicate and returns the last matching element in the entire Array .
[FindLastIndex(T], Predicate) Searches for elements that match the conditions defined by the specified predicate and returns the zero-based index of the last matching element in the entire Array .
GetValue(Int64) Get the value at the specified position in the one-dimensional Array . Indexes are specified as 64-bit integers.
IndexOf(Array, Object) Searches for the specified object in a one-dimensional array and returns the index of its first occurrence.
MemberwiseClone() Create a shallow copy of the current Object . (inherited from Object )
[Resize(T], Int32) Changes the number of elements of a one-dimensional array to the specified new size.
SetValue(Object, Int32) Sets the value to the element at the specified position in the one-dimensional Array . Indexes are specified as 32-bit integers.
Sort(Array) Sorts the elements in the entire one-dimensional Array using the IComparable implementation for each element in the Array .
ToString() Returns a string representing the current object. (inherited from Object )

Quick access to more Array methods

Five, enumeration

C# enums are value types. In other words, enumerations contain their own values ​​and cannot be inherited or passed on. An enumeration is a set of named integer constants. Enumerated types are declared using the enum keyword.

grammar:

// enum 枚举关键词 enum_name 枚举变量名
enum <enum_name>
{ 
    enumeration list // 是一个用逗号分隔的标识符列表 
};
// 示例:
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
int x = (int)Day.Sun; // x为0

Note: Each symbol in the enumerated list represents an integer value, an integer value greater than the symbol before it. By default, the value of the first enumeration symbol is 0.

6. Supplementary understanding

concept describe
Multidimensional Arrays C# supports multidimensional arrays. The simplest form of a multidimensional array is a two-dimensional array.
jagged array C# supports jagged arrays, that is, arrays of arrays.
pass the array to the function You can pass a pointer to an array to a function by specifying the array name without an index.
parameter array This is often used to pass an unknown number of arguments to a function.
Array class Defined in the System namespace, it is the base class for all arrays and provides various properties and methods for arrays.

Array to string: string.Join(",", 数组变量);

String to array: 字符串变量.Split(',');

Guess you like

Origin blog.csdn.net/IO14122/article/details/126142395