Array Methods and Properties
1. Properties
Length
The Length property gets the total number of elements in all dimensions of the array.
int[] numbers = { 10, 20, 30, 40, 50 };
int length = numbers.Length; // length = 5
Rank
The Rank property gets the number of dimensions (or rank) of the array.
int[,] matrix = new int[3, 5];
int rank = matrix.Rank; // rank = 2
2. Methods
GetValue and SetValue
The GetValue method retrieves the value at a specific position in the array, and the SetValue method sets a value at a specific position in the array.
int[] numbers = { 10, 20, 30, 40, 50 };
int value = (int) numbers.GetValue(2); // value = 30
numbers.SetValue(100, 2); // numbers[2] = 100
CopyTo
The CopyTo method copies all the elements of the current array into a specified array, starting at a specific index.
int[] sourceArray = { 1, 2, 3 };
int[] destinationArray = new int[5];
sourceArray.CopyTo(destinationArray, 2);
// destinationArray = { 0, 0, 1, 2, 3 }
Clone
The Clone method creates a shallow copy of the array.
int[] numbers = { 10, 20, 30 };
int[] clonedArray = (int[]) numbers.Clone();
Sort
The Sort method sorts the elements in a one-dimensional array.
int[] numbers = { 30, 10, 20 };
Array.Sort(numbers); // numbers = { 10, 20, 30 }
Reverse
The Reverse method reverses the order of the elements in a one-dimensional array.
int[] numbers = { 30, 10, 20 };
Array.Reverse(numbers); // numbers = { 30, 20, 10 }
IndexOf
The IndexOf method returns the index of the first occurrence of a value in a one-dimensional array.
int[] numbers = { 10, 20, 30 };
int index = Array.IndexOf(numbers, 20); // index = 1
Find
The Find method returns the first element that satisfies the conditions defined by a specified predicate.
int[] numbers = { 10, 20, 30 };
int result = Array.Find(numbers, element => element > 15); // result = 20
FindAll
The FindAll method returns all elements that satisfy the conditions defined by a specified predicate.
int[] numbers = { 10, 20, 30, 40 };
int[] results = Array.FindAll(numbers, element => element > 15); // results = { 20, 30, 40 }