This post will discuss how to remove the specified element from an array in C#.

We know that arrays in C# have fixed size, and we cannot simply remove an element from it. However, we can create a new array containing the desired elements from the original arrays. This post provides an overview of some of the available alternatives to accomplish this.

Remove all occurrences of an element from an array:

1. Enumerable.Where() method (System.Linq)

The System.Linq.Enumerable.Where() method filters a sequence of values based on a predicate. The following code example demonstrates how we can use Where() to remove all occurrences of an element from the array.

Download  Run Code

2. Array.FindAll() method

Array.FindAll() method returns an array containing all the elements that match the specified predicate. Following is a simple example demonstrating usage of this method:

Download  Run Code

3. Enumerable.Except() method (System.Linq)

Another solution is to use the Enumerable.Except() method, which compares two sequences and returns the elements that appear only in the first sequence. This method is demonstrated below:

Download  Run Code

Remove only first occurrence of element from an array:

The following code example demonstrates how we can use Where() to remove only the first occurrence of an element from the array.

Download  Run Code

 
We can also convert the array to a list and call its RemoveAt() method to remove the element’s first occurrence. Then, we convert the list back to the array using the ToArray() method.

Download  Run Code

That’s all about removing the specified element from an array in C#.