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
- C#
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
- C#
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
- C#
int firstElement = intArray[0]; // Access first element
String Array
- C#
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
- C#
intArray[1] = 10; // Modify second element
String Array
- C#
stringArray[1] = "blueberry"; // Modify second element
4. Length of Array
The length property provides the number of elements in the array.
Integer Array
- C#
int length = intArray.Length; // Get length
String Array
- C#
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
- C#
for (int i = 0; i < intArray.Length; i++)
{
Console.WriteLine(intArray[i]);
}
Foreach Loop
- C#
foreach (int number in intArray)
{
Console.WriteLine(number);
}
6. Sorting an Array
Arrays can be sorted using the Array.Sort
method.
Integer Array
- C#
Array.Sort(intArray); // Sort array
String Array
- C#
Array.Sort(stringArray); // Sort array
7. Reversing an Array
The Array.Reverse
method reverses the order of elements in the array.
Integer Array
- C#
Array.Reverse(intArray); // Reverse array
String Array
- C#
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
- C#
int index = Array.IndexOf(intArray, 3); // Find index of element
String Array
- C#
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
- C#
int[] newArray = new int[intArray.Length];
Array.Copy(intArray, newArray, intArray.Length);
String Array
- C#
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
- C#
int[] cloneArray = (int[])intArray.Clone();
String Array
- C#
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
- C#
Array.Resize(ref intArray, 10); // Resize array
String Array
- C#
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
- C#
Array.Clear(intArray, 0, intArray.Length); // Clear array
String Array
- C#
Array.Clear(stringArray, 0, stringArray.Length); // Clear array
13. Using LINQ
LINQ provides a powerful way to query and manipulate arrays.
Filtering
- C#
int[] filteredArray = intArray.Where(x => x > 2).ToArray();
string[] filteredArray = stringArray.Where(s => s.Contains("a")).ToArray();
Select
- C#
var squaredArray = intArray.Select(x => x * x).ToArray();
var upperArray = stringArray.Select(s => s.ToUpper()).ToArray();
Aggregate
- C#
int sum = intArray.Aggregate((acc, x) => acc + x);
string concatenated = stringArray.Aggregate((acc, s) => acc + s);
GroupBy
- C#
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
- C#
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
- C#
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
- C#
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
- C#
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
- C#
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
- C#
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
- C#
int count = intArray.Count(x => x > 2);
int count = stringArray.Count(s => s.Contains("a"));
20. Binary Search
The Array.BinarySearch
method performs a binary search on a sorted array.
Binary Search
- C#
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
- C#
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
- C#
int[] unionArray = intArray.Union(new int[] {3, 4}).ToArray();
string[] unionArray = stringArray.Union(new string[] {"apple", "banana"}).ToArray();
Intersection
- C#
int[] intersectArray = intArray.Intersect(new int[] {3, 4}).ToArray();
string[] intersectArray = stringArray.Intersect(new string[] {"apple", "banana"}).ToArray();
Except
- C#
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
- C#
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
- C#
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
- C#
int[,] multiArray = new int[2, 3] {{1, 2, 3}, {4, 5, 6}};
Accessing Elements
- C#
int element = multiArray[0, 1]; // 2
Modifying Elements
- C#
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
- C#
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
- C#
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
- C#
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
- C#
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
- C#
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
- C#
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
- C#
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
- C#
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
- C#
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
- C#
- Python
- JavaScript
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
int_list = [1, 2, 3, 4]
int_list.pop() # Remove from the end
int_list.pop(1) # Remove at specific position
string_list = ["apple", "banana", "cherry", "date"]
string_list.pop() # Remove from the end
string_list.pop(1) # Remove at specific position
let intList = [1, 2, 3, 4];
intList.pop(); // Remove from the end
intList.splice(1, 1); // Remove at specific position
let stringList = ["apple", "banana", "cherry", "date"];
stringList.pop(); // Remove from the end
stringList.splice(1, 1); // Remove at specific position
29. Finding the Average
The Average
method calculates the average of the elements in an array.
Average
- C#
double average = intArray.Average();
30. Converting Array to String
You can convert an array to a string using the String.Join
method.
Join
- C#
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
- C#
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
- C#
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
- C#
var pool = ArrayPool<int>.Shared;
int[] rentedArray = pool.Rent(10);
try
{
// Use the array
}
finally
{
pool.Return(rentedArray);
}
If you have enjoyed this post, please consider buying me a coffee ☕ to help me keep writing!