Skip to main content

List of Array manipulation operations

The comprehensive list of array manipulations in with examples, including add and remove operations.

1. Initialization

Arrays in C# can be initialized either with predefined values or by specifying the size and then assigning values later.

Integer Array

int[] intArray = {1, 2, 3, 4, 5};
int[] intArray2 = new int[5]; // Array with 5 elements
intArray2[0] = 1; // Assign values one by one

String Array

string[] stringArray = {"apple", "banana", "cherry"};
string[] stringArray2 = new string[3]; // Array with 3 elements
stringArray2[0] = "apple";

2. Accessing Elements

You can access individual elements in an array using their index.

Integer Array

int firstElement = intArray[0]; // Access first element

String Array

string firstElement = stringArray[0]; // Access first element

3.Modifying elements

Elements in an array can be modified by directly assigning new values to specific indices.

Integer Array

intArray[1] = 10; // Modify second element

String Array

stringArray[1] = "blueberry"; // Modify second element

4. Length of Array

The length property provides the number of elements in the array.

Integer Array

int length = intArray.Length; // Get length

String Array

int length = stringArray.Length; // Get length

5. Iterating through an Array

You can iterate over an array using loops to process or display each element.

For Loop

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

Foreach Loop

foreach (int number in intArray)
{
Console.WriteLine(number);
}

6. Sorting an Array

Arrays can be sorted using the Array.Sort method.

Integer Array

Array.Sort(intArray); // Sort array

String Array

Array.Sort(stringArray); // Sort array

7. Reversing an Array

The Array.Reverse method reverses the order of elements in the array.

Integer Array

Array.Reverse(intArray); // Reverse array

String Array

Array.Reverse(stringArray); // Reverse array

8. Finding Elements

The Array.IndexOf and Array.LastIndexOf methods are used to find the index of a specific element.

Integer Array

int index = Array.IndexOf(intArray, 3); // Find index of element

String Array

int index = Array.LastIndexOf(stringArray, "apple"); // Find last index of element

9. Copying an Array

Arrays can be copied to another array using the Array.Copy method.

Integer Array

int[] newArray = new int[intArray.Length];
Array.Copy(intArray, newArray, intArray.Length);

String Array

string[] newArray = new string[stringArray.Length];
Array.Copy(stringArray, newArray, stringArray.Length);

10. Cloning an Array

The Clone method creates a shallow copy of the array.

Integer Array

int[] cloneArray = (int[])intArray.Clone();

String Array

string[] cloneArray = (string[])stringArray.Clone();

11. Resizing an Array

Arrays can be resized using the Array.Resize method, although this creates a new array with the specified size.

Integer Array

Array.Resize(ref intArray, 10); // Resize array

String Array

Array.Resize(ref stringArray, 5); // Resize array

12. Clearing an Array

The Array.Clear method sets all elements in the array to their default values (e.g., 0 for int, null for string).

Integer Array

Array.Clear(intArray, 0, intArray.Length); // Clear array

String Array

Array.Clear(stringArray, 0, stringArray.Length); // Clear array

13. Using LINQ

LINQ provides a powerful way to query and manipulate arrays.

Filtering

int[] filteredArray = intArray.Where(x => x > 2).ToArray();
string[] filteredArray = stringArray.Where(s => s.Contains("a")).ToArray();

Select

var squaredArray = intArray.Select(x => x * x).ToArray();
var upperArray = stringArray.Select(s => s.ToUpper()).ToArray();

Aggregate

int sum = intArray.Aggregate((acc, x) => acc + x);
string concatenated = stringArray.Aggregate((acc, s) => acc + s);

GroupBy

var grouped = intArray.GroupBy(x => x % 2 == 0);
foreach (var group in grouped)
{
Console.WriteLine(group.Key ? "Even" : "Odd");
foreach (var number in group)
{
Console.WriteLine(number);
}
}

OrderBy and ThenBy

var ordered = stringArray.OrderBy(s => s.Length).ThenBy(s => s);
foreach (var str in ordered)
{
Console.WriteLine(str);
}

14. Joining Arrays

Arrays can be joined using the Concat method.

Concat

int[] combinedArray = intArray.Concat(new int[] {6, 7}).ToArray();
string[] combinedArray = stringArray.Concat(new string[] {"date", "fig"}).ToArray();

15. Checking for Elements

You can check if an array contains a specific element using the Contains method.

Contains

bool containsElement = intArray.Contains(3);
bool containsElement = stringArray.Contains("apple");

16. Creating Subarrays

Subarrays can be created using LINQ's Skip and Take methods or by using ArraySegment.

Skip and Take

int[] subArray = intArray.Skip(2).Take(3).ToArray();
string[] subArray = stringArray.Skip(1).Take(2).ToArray();

17. Finding Min and Max

The Min and Max methods can be used to find the minimum and maximum values in an array.

Min and Max

int min = intArray.Min();
int max = intArray.Max();

string minValue = stringArray.Min();
string maxValue = stringArray.Max();

18. Summing Elements

The Sum method sums up all elements in an array.

Sum

int sum = intArray.Sum(); // Not directly applicable for strings, but can use Aggregate or other methods for
custom aggregation

19. Counting Elements

The Count method counts the number of elements that match a specific condition.

Count

int count = intArray.Count(x => x > 2);
int count = stringArray.Count(s => s.Contains("a"));

The Array.BinarySearch method performs a binary search on a sorted array.

int index = Array.BinarySearch(intArray, 3);
int index = Array.BinarySearch(stringArray, "apple");

21. Finding Distinct Elements

The Distinct method returns distinct elements in an array.

Distinct

int[] distinctArray = intArray.Distinct().ToArray();
string[] distinctArray = stringArray.Distinct().ToArray();

22. Finding Union, Intersection, Difference

You can find the union, intersection, and difference of arrays using LINQ methods.

Union

int[] unionArray = intArray.Union(new int[] {3, 4}).ToArray();
string[] unionArray = stringArray.Union(new string[] {"apple", "banana"}).ToArray();

Intersection

int[] intersectArray = intArray.Intersect(new int[] {3, 4}).ToArray();
string[] intersectArray = stringArray.Intersect(new string[] {"apple", "banana"}).ToArray();

Except

int[] exceptArray = intArray.Except(new int[] {3, 4}).ToArray();
string[] exceptArray = stringArray.Except(new string[] {"apple", "banana"}).ToArray();

23. Converting Array to List

Arrays can be converted to lists using the ToList method.

ToList

List<int> intList = intArray.ToList();
List<string> stringList = stringArray.ToList();

24. Converting List to Array

Lists can be converted to arrays using the ToArray method.

ToArray

List<int> intList = new List<int> {1, 2, 3, 4, 5};
int[] intArray = intList.ToArray();
List<string> stringList = new List<string> {"apple", "banana", "cherry"};
string[] stringArray = stringList.ToArray();

25. Multidimensional Arrays

C# supports multidimensional arrays (arrays of arrays).

Initialization

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

Accessing Elements

int element = multiArray[0, 1]; // 2

Modifying Elements

multiArray[1, 2] = 10;

26. Add Operations

Since arrays in C# are of fixed size, adding elements requires creating a new array and copying the elements.

Adding an Element to the End

Integer Array

int[] intArray = {1, 2, 3};
int[] newArray = new int[intArray.Length + 1];
for (int i = 0; i < intArray.Length; i++)
{
newArray[i] = intArray[i];
}
newArray[newArray.Length - 1] = 4; // Add new element

String Array

string[] stringArray = {"apple", "banana", "cherry"};
string[] newArray = new string[stringArray.Length + 1];
for (int i = 0; i < stringArray.Length; i++)
{
newArray[i] = stringArray[i];
}
newArray[newArray.Length - 1] = "date"; // Add new element

Adding an Element at a Specific Index

Integer Array

int[] intArray = {1, 2, 3};
int[] newArray = new int[intArray.Length + 1];
int index = 1; // Position to insert new element
for (int i = 0; i < index; i++)
{
newArray[i] = intArray[i];
}
newArray[index] = 10; // New element
for (int i = index; i < intArray.Length; i++)
{
newArray[i + 1] = intArray[i];
}

String Array

string[] stringArray = {"apple", "banana", "cherry"};
string[] newArray = new string[stringArray.Length + 1];
int index = 1; // Position to insert new element
for (int i = 0; i < index; i++)
{
newArray[i] = stringArray[i];
}
newArray[index] = "date"; // New element
for (int i = index; i < stringArray.Length; i++)
{
newArray[i + 1] = stringArray[i];
}

27. Remove Operations

To remove an element, a new array must be created with a reduced size, and elements must be copied over, excluding the element to be removed.

Removing an Element from the End

Integer Array

int[] intArray = {1, 2, 3, 4};
int[] newArray = new int[intArray.Length - 1];
for (int i = 0; i < newArray.Length; i++)
{
newArray[i] = intArray[i];
}

String Array

string[] stringArray = {"apple", "banana", "cherry", "date"};
string[] newArray = new string[stringArray.Length - 1];
for (int i = 0; i < newArray.Length; i++)
{
newArray[i] = stringArray[i];
}

Removing an Element at a Specific Index

Integer Array

int[] intArray = {1, 2, 3, 4};
int[] newArray = new int[intArray.Length - 1];
int index = 1; // Position to remove element
for (int i = 0; i < index; i++)
{
newArray[i] = intArray[i];
}
for (int i = index + 1; i < intArray.Length; i++)
{
newArray[i - 1] = intArray[i];
}

String Array

string[] stringArray = {"apple", "banana", "cherry", "date"};
string[] newArray = new string[stringArray.Length - 1];
int index = 1; // Position to remove element
for (int i = 0; i < index; i++)
{
newArray[i] = stringArray[i];
}
for (int i = index + 1; i < stringArray.Length; i++)
{
newArray[i - 1] = stringArray[i];
}

28. Using List<T> for Dynamic Add and Remove

Using List<T> is a more flexible approach for dynamic collections as it allows for easy addition and removal of elements.

Adding Elements

List<int> intList = new List<int> {1, 2, 3};
intList.Add(4); // Add to the end
intList.Insert(1, 10); // Add at specific position

List<string> stringList = new List<string> {"apple", "banana", "cherry"};
stringList.Add("date"); // Add to the end
stringList.Insert(1, "blueberry"); // Add at specific position

Removing Elements

List<int> intList = new List<int> {1, 2, 3, 4};
intList.RemoveAt(intList.Count - 1); // Remove from the end
intList.RemoveAt(1); // Remove at specific position

List<string> stringList = new List<string> {"apple", "banana", "cherry", "date"};
stringList.RemoveAt(stringList.Count - 1); // Remove from the end
stringList.RemoveAt(1); // Remove at specific position

29. Finding the Average

The Average method calculates the average of the elements in an array.

Average

double average = intArray.Average();

30. Converting Array to String

You can convert an array to a string using the String.Join method.

Join

string arrayString = String.Join(", ", intArray);
string arrayString = String.Join(", ", stringArray);

31. Using Span<T> for Performance

Span<T> provides a way to work with slices of arrays without allocations.

Span

Span
<int> span = intArray.AsSpan().Slice(1, 3);
foreach (var number in span)
{
Console.WriteLine(number);
}

32. Using Memory<T> for Asynchronous Operations

Memory<T> is similar to Span<T> but can be used in asynchronous methods.

Memory

Memory<int> memory = new Memory<int>(intArray);
await ProcessMemoryAsync(memory);
async Task ProcessMemoryAsync(Memory<int> memory)
{
foreach(var number in memory.Span)
{
await Task.Delay(100); // Simulate async work
Console.WriteLine(number);
}
}

33. Using ArrayPool<T> for Efficient Memory Usage

ArrayPool<T> allows for efficient reuse of arrays to minimize allocations.

ArrayPool

var pool = ArrayPool<int>.Shared;
int[] rentedArray = pool.Rent(10);
try
{
// Use the array
}
finally
{
pool.Return(rentedArray);
}
Every Bit of Support Helps!

If you have enjoyed this post, please consider buying me a coffee ☕ to help me keep writing!