Summary of Common Operation Methods of C Array

  • 2021-10-11 19:19:11
  • OfStack

1. How arrays are declared and assigned


int[] myArray;

int[] myArray = {1, 2, 3, 4};

int[] myArray = new int[4] {1, 2, 3, 4};

2. Declaration of multidimensional arrays


int[,] myArray = new int[2, 3];

int[,] myArray = {
{1, 2, 3},
{1, 2, 3}
};

To get a multidimensional array element, you can use:


myArray[0, 1]; // 2

3. Declaration of Sawtooth Arrays


int[][] myArray = new int[2][];

myArray[0] = new int[2] {1, 2};
myArray[1] = new int[3] {1, 2,3};

To get a sawtooth array element, you can use:


myArray[0][1]; // 2

4. Getting Array Elements

Available through the subscript index:


myArray[0];

You can also use the GetValue () method to read the value of the corresponding element;

The SetValue () method sets the value of the corresponding element.

5. foreach cycle


string[] myArray = {"alily", "swen", "ben", "cat"};
foreach (var value in myArray) {
  Console.Write(value); // alily, swen, ben, cat
}

6. Copy an array

The Clone () method creates a superficial copy of the array. If the elements of the array are value types, Clone () copies all values; If the array contains reference types, the elements are not copied, but the references are copied.


//  When an array element is a value type, Clone() Copy all values 
int[] intArray = {1, 2, 3};
int[] intArrayClone = (int[]) intArray.Clone(); // intArrayClone = {1, 2, 3}

//  When an array element contains a reference type, only the reference is copied 
Person[] girl = {new Person{FirstName = "Sam", LastName = "Lennon"}, new Person{FirstName = "Ben", LastName = "Cartney"}};
Person[] girlClone = (Person[]) girl.Clone(); // girl And girlClone Quoted Person Object is the same when modifying girlClone Medium 1 Reference to the attributes of type elements, it also changes girl Corresponding object in 

The Copy () method creates a superficial copy.

Important differences between Clone () method and Copy () method:

The Clone () method creates a new array, while the Copy () method must pass an existing array of the same order with enough elements.

If you need a deep copy of an array containing reference types, you must iterate over the array and create an object.

7. Array sorting

The static method Sort () in the Array class sorts arrays


int[] num =new int[] { 5,2,3,4,1 };

Array.Sort(num);

foreach(int i in num)

Console.WriteLine(i);

Output:


1

2

3

4

5

8. Array comparison

CompareTo (). Returns 0 if the compared objects are equal; Returns a negative number if the parameter instance should be in front of the parameter object, or a positive number if not.


int[,] myArray = new int[2, 3];

int[,] myArray = {
{1, 2, 3},
{1, 2, 3}
};

0


Related articles: