Array manipulations in C#

Mohammad Zubair 0
Logo

Here’s a comprehensive guide to various basic to advanced array operations in C#:

1. Declaration and Initialization:

int[] numbers = new int[5]; 
// Declaration with a specified length
int[] primes = { 2, 3, 5, 7, 11 }; 
// Declaration with initialization

2. Accessing Array Elements:

int firstElement = primes[0]; // Accessing the first element
int lastElement = primes[primes.Length - 1]; // Accessing the last element

3. Iterating Through an Array:

foreach (int prime in primes)
{
Console.WriteLine(prime);
}

for (int i = 0; i < primes.Length; i++)
{
Console.WriteLine(primes[i]);
}

4. Array Methods:

int[] copyArray = (int[])primes.Clone(); // Creates a shallow copy of the array
int[] subArray = primes[1..3]; // Creates a subarray using range syntax
int[] reversedArray = primes.Reverse().ToArray(); // Reverses the array
Array.Sort(primes); // Sorts the array in ascending order
Array.Sort(primes, (x, y) => y.CompareTo(x)); // Custom sorting
Array.Resize(ref primes, 10); // Resizes the array

5. Searching and Indexing:

int index = Array.IndexOf(primes, 7); // Finds the index of an element
bool contains = primes.Contains(5); // Checks if an element exists in the array
int foundIndex = Array.FindIndex(primes, x => x > 5); // Finds the index based on a condition
int foundElement = Array.Find(primes, x => x > 5); // Finds the first element based on a condition

6. Array Copying:

int[] destinationArray = new int[primes.Length];
Array.Copy(primes, destinationArray, primes.Length); // Copy elements to a new array
primes.CopyTo(destinationArray, 0); // Copy elements to an existing array

7. Multidimensional Arrays:

int[,] matrix = new int[3, 3]; // Declaration of a 2D array
matrix[0, 0] = 1; // Accessing elements of a 2D array

int[,,] cube = new int[2, 2, 2]; // Declaration of a 3D array

8. Jagged Arrays:

int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };

9. LINQ with Arrays:

var evenPrimes = primes.Where(x => x % 2 == 0); // Filter using LINQ
var squaredPrimes = primes.Select(x => x * x); // Transform using LINQ
var sum = primes.Sum(); // Calculate the sum using LINQ
Thanks for reading.

Mohammad Zubair

I'm Mohammad Zubair, a passionate software engineer working in the dynamic world of IT. Currently, I'm proud to be a part of HawarIT, a thriving Dutch-Bangladeshi joint venture company, where I contribute my expertise and enthusiasm to the field of software engineering.

Leave a Reply

Your email address will not be published. Required fields are marked *