SoFunction
Updated on 2025-03-07

Summary of common operation methods for C# arrays

1. Declaration and assignment method of array

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 multi-dimensional array elements, you can use:

myArray[0, 1]; // 2

3. Declaration of jagged arrays

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

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

To get the jagged array element, you can use:

myArray[0][1]; // 2

4. Getting array elements

Can be obtained 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 loop

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

6. Copy the array

The Clone() method creates a shallow copy of an array. If the element of the array is of a value type, Clone() copies all values; if the array contains a reference type, the element is not copied, but the reference is copied.

// When the array element is a value type, Clone() copies all valuesint[] intArray = {1, 2, 3};
int[] intArrayClone = (int[]) (); // intArrayClone = {1, 2, 3}

// When the array element contains a reference type, only the reference is copiedPerson[] girl = {new Person{FirstName = "Sam", LastName = "Lennon"}, new Person{FirstName = "Ben", LastName = "Cartney"}};
Person[] girlClone = (Person[]) (); // The Person objects referenced by girl and girlClone are the same. When modifying the attribute of a reference type element in girlClone, the corresponding object in girl will also be changed.

The Copy() method creates a shallow 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 and sufficient elements.

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

7. Array sorting

Sort() static method sorting array in Array class

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

(num);

foreach(int i in num)

(i);

Output:

1

2

3

4

5

8. Array comparison

CompareTo(). Returns 0 if the comparison objects are equal; returns negative if the parameter instance should be ahead of the parameter object, otherwise returns positive.

string a = "world";
string b = "hello";
int result = (b); // Return a negative number