Default Method of Array

Default Method of Array

Β·

1 min read

1. Array.Sort() 🧹: Sorts the elements of an array in ascending order.

int[] numbers = { 3, 1, 4, 1, 5, 9 };
Array.Sort(numbers); // numbers will be { 1, 1, 3, 4, 5, 9 }

2. Array.Reverse() πŸ”„: Reverses the order of elements in an array.

Array.Reverse(numbers); // numbers will be { 9, 5, 4, 3, 1, 1 }

3. Array.Copy() πŸ“‹: Copies a range of elements from one array to another.

int[] sourceArray = { 10, 20, 30, 40, 50 };
int[] destinationArray = new int[3];

// Copy 3 elements from index 1 of the source array to index 0 of the destination array
Array.Copy(sourceArray, 1, destinationArray, 0, 3);

// Now, the destinationArray will contain { 20, 30, 40 }

// Array.Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length);

4. Array.IndexOf() πŸ”: Finds the index of the first occurrence of a specific element.

int index = Array.IndexOf(numbers, 4); // index will be 2

5. Array.LastIndexOf() πŸ”Ž: Finds the index of the last occurrence of a specific element.

int lastIndex = Array.LastIndexOf(numbers, 1); // lastIndex will be 1

Note: We don’t have a direct sorting of Array descending order, but we can use Array.Sort() and then Array.Reverse() to achieve it.

Β