How to Remove Element of an Array in C#
Minahil Noor
Feb 02, 2024
-
Use the
where()
Clause to Remove the Element of an Array inC#
-
Use the Shifting Program to Remove the Element of an Array in
C#
This article will introduce different methods to remove the element of a regular array using C# code, like the where()
clause and the shifting program.
Use the where()
Clause to Remove the Element of an Array in C#
In C#, there is no such method to remove or add elements to an existing array. That is why it is recommended to use a list instead of an array. But we can use LINQ’s where()
clause to find the index of the element to remove and skip the element. After that, we will convert the array into a new array without the specified element.
The program below shows how we can use the where()
clause to remove the element of a regular array.
using System;
using System.Linq;
class StringToFloat {
static void Main(string[] args) {
string[] myArray = { "a", "b", "c", "d", "e" };
Console.WriteLine("Array before deletion");
foreach (string value in myArray) {
Console.WriteLine(value);
}
int indexToRemove = 3;
myArray = myArray.Where((source, index) => index != indexToRemove).ToArray();
Console.WriteLine("Array after deletion");
foreach (string value in myArray) {
Console.WriteLine(value);
}
}
}
Output:
Array before deletion
a
b
c
d
e
Array after deletion
a
b
c
e
Use the Shifting Program to Remove the Element of an Array in C#
We will use the element shifting program to remove the element of a regular array.
The element shifting program is as follows.
using System;
using System.Linq;
class StringToFloat {
static void Main(string[] args) {
string[] myArray = { "a", "b", "c", "d", "e" };
Console.WriteLine("Array before deletion");
foreach (string value in myArray) {
Console.WriteLine(value);
}
int pos = 3;
int i;
for (i = pos - 1; i < 4; i++) {
myArray[i] = myArray[i + 1];
}
Console.WriteLine("Array after deletion");
for (i = 0; i < 4; i++) {
Console.WriteLine(myArray[i]);
}
}
}
Output:
Array before deletion
a
b
c
d
e
Array after deletion
a
b
d
e