Updated on
A C# array has a fixed size, so we can’t remove an element from it in place. We build a new array without that element instead, with Array.Copy(), a collection expression, LINQ’s Where() or a List<T>.
Some of these remove only the first instance of a value, and others remove every instance. At the end, we benchmark most of them on .NET 11 to help you choose the best option for your specific use case.
Let’s begin!
Arrays in .NET
Arrays are a fundamental data structure in .NET, allowing developers to easily store and manipulate collections of data. However, deleting elements from an array can be a challenging task, as the size of the array is fixed once we initialize it.
To overcome this, we will demonstrate various techniques to remove elements from an array, each with its advantages and disadvantages.
Why Doesn’t a C# Array Have a Remove Method?
An array in C# has a fixed length. We set it when we create the array, and nothing can shrink it afterwards. That is why the Array type has no Remove() method of its own.
Arrays do implement IList<T>, so Remove() and RemoveAt() exist on that interface. On an array, both throw a NotSupportedException with the message “Collection was of a fixed size.”
So deleting an element means building a new array that holds every element except the one we don’t want, and using that array from then on. Even Array.Resize() works this way: it allocates a new array and copies into it.
Two questions separate the approaches in this article. Do we remove only the first instance of a value, or every instance? And how much copying and allocation does it cost us?
If we delete elements often, a List<T> is usually the better container from the start.
Here is what that looks like in code, on the six-element sample array we set up below:
try
{
((IList<int>)array).Remove(3);
}
catch (NotSupportedException ex)
{
Console.WriteLine(ex.Message);
}
The call compiles, but it fails at run time and the array keeps all six elements:
Collection was of a fixed size.
The solutions are built with integer arrays for demonstration purposes, but we can apply all of them except Buffer.BlockCopy() to any data type.
We’ll start by setting up a simple example to test against our methods:
int[] array = [3, 4, 5, 3, 5, 7]; var elementToDelete = 3;
Here, we construct an array of integers and we assign to the elementToDelete variable the value we want to remove from our collection. These two lines go at the top of Program.cs, under a using static Methods; line, and the removal methods that follow go in a Methods class.
Clearing an array is a different job. If we want to keep the length and only reset the values, Array.Clear() sets elements back to their default value, which is 0 for an int:
int[] numbers = [3, 4, 5, 6];
Array.Clear(numbers, 1, 2);
Console.WriteLine(string.Join(",", numbers));
The array still has four elements, and the two we cleared are now zeros:
3,0,0,6
Called with just the array, Array.Clear(numbers) resets every element.
Use Array.Copy() To Delete an Element From an Array
First, we will remove it with the static Array.Copy() method:
public int[] DeleteWithArrayCopy(int[] inputArray, int elementToRemove)
{
var indexToRemove = Array.IndexOf(inputArray, elementToRemove);
if (indexToRemove < 0)
{
return inputArray;
}
var tempArray = new int[inputArray.Length - 1];
Array.Copy(inputArray, 0, tempArray, 0, indexToRemove);
Array.Copy(inputArray, indexToRemove + 1, tempArray, indexToRemove, inputArray.Length - indexToRemove - 1);
return tempArray;
}
The DeleteWithArrayCopy() method takes as arguments an inputArray integer array and an elementToRemove integer.
First, we find the index of the elementToRemove integer in the inputArray array using the built-in Array.IndexOf() method.
If the elementToRemove is not found in the inputArray, we simply return the inputArray.
Otherwise, we create a new integer array tempArray with length that is one less than the inputArray array’s length. Then, we copy all elements from the original array except the elementToRemove into it using the Copy() method. Finally, we return the tempArray array.
Array.Copy() has a few more overloads, and we cover them in our article on copying an array in C#.
So we end up with:
With ArrayCopy: 4,5,3,5,7
As we expect, the new array does not include the first instance of element “3”. The remaining elements have been moved to the left and the new array has a size of five elements.
Remove First Instance of Element Using ArraySegment
Next, we can make use of the ArraySegment struct, which consists of a reference to the original array, an offset indicating the starting index of the segment in the array, and a count indicating the number of elements in the segment.
Let’s see it in action:
public int[] DeleteWithArraySegment(int[] inputArray, int elementToRemove)
{
var indexToRemove = Array.IndexOf(inputArray, elementToRemove);
if (indexToRemove < 0)
{
return inputArray;
}
int[] tempArray;
var segment1 = new ArraySegment<int>(inputArray, 0, indexToRemove);
var segment2 = new ArraySegment<int>(inputArray, indexToRemove + 1, inputArray.Length - indexToRemove - 1);
tempArray = segment1.Concat(segment2).ToArray();
return tempArray;
}
First, we find the index position of the given element. If it does not exist, we return the inputArray array as is, as there are no elements to remove.
Otherwise, we construct two new ArraySegment objects. We create an ArraySegment object from the beginning of the inputArray to the index of the element to remove. Then, we create a second one from the right next position of the calculated index to the end of the inputArray.
Finally, we store the concatenation of these two segments into the tempArray using the Concat() method and convert the resulting IEnumerable to an array using the ToArray() method.
Concat() and ToArray() come from LINQ, while the segments themselves copy nothing: each one is just a view over part of inputArray. We take a closer look at the type itself in our article on ArraySegment<T> in C#.
Use a For Loop to Remove an Element
Our next solution makes use of a loop and a temporary array:
public int[] DeleteWithLoop(int[] inputArray, int elementToRemove)
{
var indexToRemove = Array.IndexOf(inputArray, elementToRemove);
if (indexToRemove < 0)
{
return inputArray;
}
var tempArray = new int[inputArray.Length - 1];
for (int i = 0, j = 0; i < inputArray.Length; i++)
{
if (i == indexToRemove)
{
continue;
}
tempArray[j] = inputArray[i];
j++;
}
return tempArray;
}
If the element does not exist in the array, we return the original inputArray. Differently, we create a new integer tempArray array of size equal to the size of inputArray decreased by one.Â
Then, we use a for loop to iterate through the inputArray, copying each element to the corresponding position in tempArray except for the elementToRemove.
Finally, we return the tempArray which does not include the first instance of the specified element.
Also, we can refactor this method to shift the elements in place and then use the Array.Resize() method. Since this version replaces the array we pass in with a new, shorter one, it takes the array by ref:
public static void DeleteWithLoopAndResize(ref int[] inputArray, int elementToRemove)
{
var indexToRemove = Array.IndexOf(inputArray, elementToRemove);
if (indexToRemove >= 0)
{
for (int i = indexToRemove; i < inputArray.Length - 1; i++)
{
inputArray[i] = inputArray[i + 1];
}
Array.Resize(ref inputArray, inputArray.Length - 1);
}
}
Here, in the for loop, we shift every element after the indexToRemove one position to the left.
Then, we decrease the array size by one, with the use of the Array.Resize() method. To achieve this, we pass the array as a reference and the new length.Â
Array.Resize() doesn’t shrink the array in place, though. The Microsoft Learn page for the method says it “allocates a new array with the specified size” and then copies the elements into it. So this version allocates a new array just like the others, and it writes to the original array first.
To keep our sample array intact for the other methods, we resize a clone of it:
var resizedArray = (int[])array.Clone(); DeleteWithLoopAndResize(ref resizedArray, elementToDelete);
Which gives us:
With Loop and Resize: 4,5,3,5,7
However, we need to be cautious when we change arrays in place. Without ref, a method like this shifts the caller’s array and then resizes only its own copy of the reference. With our sample array, the caller would be left holding 4,5,3,5,7,7. Any other variable that points to the same array sees the shifted values too. And if multiple threads access that array, it can lead to race conditions and other synchronization problems.
Remove an Element with the Use of Buffer.BlockCopy()
Also, we can use the static BlockCopy() method of the Buffer class for removing an element:
public static int[] DeleteWithBufferCopy(int[] inputArray, int elementToRemove)
{
var indexToRemove = Array.IndexOf(inputArray, elementToRemove);
if (indexToRemove < 0)
{
return inputArray;
}
var tempArray = new int[inputArray.Length - 1];
Buffer.BlockCopy(inputArray, 0, tempArray, 0, indexToRemove * sizeof(int));
Buffer.BlockCopy(inputArray,
(indexToRemove + 1) * sizeof(int),
tempArray,
indexToRemove * sizeof(int),
(inputArray.Length - indexToRemove - 1) * sizeof(int));
return tempArray;
}
First, we check if the element to remove is actually in the inputArray by using the Array.IndexOf() method. If the element does not exist, we return the original inputArray. Otherwise, we create the tempArray, with a length of one less than the inputArray.
Then, we use the Buffer.BlockCopy() method to copy the elements from the inputArray into the tempArray. The first parameter is the source array, from which we copy the data. The second parameter is the starting byte offset in the source array from where the copying starts. The third parameter is our destination array and the fourth parameter is the starting byte offset in the destination array where we store the copied data. The last argument specifies the number of bytes to copy.
When we use the Buffer.BlockCopy() method to copy integers, we multiply the second, fourth, and fifth parameters by sizeof(int), which is 4, because the method counts bytes, not elements.
The first call to the Buffer.BlockCopy() method copies the elements before the index of the element to remove. The second call copies the elements after that index.
Buffer.BlockCopy() only works on arrays of primitive types such as int or double, and of enums. If we pass it a string[], it throws an ArgumentException.
Finally, we return the tempArray. We use this method to efficiently remove an element from an array without having to manually shift elements around.
Remove an Element With a Collection Expression
Collection expressions give us a shorter way to build the new array. We take a span over the input array, slice it into the part before the element and the part after it, and spread both parts into a new array:
public static int[] DeleteWithCollectionExpression(int[] inputArray, int elementToRemove)
{
var indexToRemove = Array.IndexOf(inputArray, elementToRemove);
if (indexToRemove < 0)
{
return inputArray;
}
var span = inputArray.AsSpan();
return [.. span[..indexToRemove], .. span[(indexToRemove + 1)..]];
}
As before, we find the index first and return the input array when the element isn’t there.
AsSpan() doesn’t copy anything, and slicing a span with a range doesn’t either. The only copy happens when the collection expression builds the result, which is exactly as long as the two slices together.
Like the methods before it, this one removes only the first instance of the element:
With CollectionExpression: 4,5,3,5,7
How Do We Remove the First Element From an Array in C#?
Removing the first element is the easy case, because we already know its index. A range does it in one expression: inputArray[1..] returns every element from index 1 to the end.
On an array, a range creates a new array, so the original stays as it was. With our sample array, we get 4,5,3,5,7. The same syntax removes the last element too, with array[..^1].
On an empty array, though, inputArray[1..] throws an ArgumentOutOfRangeException, so if the array can be empty, we check its Length first. A one-element array is fine and gives us an empty array.
This is a different job from the methods above. They search for a value and remove its first instance, wherever it sits. Here, we drop whatever is at index 0, whatever its value is.
In our sample, that is a one-line method:
public static int[] DeleteFirstElement(int[] inputArray)
{
return inputArray[1..];
}
Ranges can do a lot more than this, and we cover them in our article on array slicing.
Delete Multiple Elements With the Where() Extension
Next, we can use the Where() extension method of LINQ:
public int[] DeleteWithWhere(int[] inputArray, int elementToRemove)
{
return inputArray.Where(e => e != elementToRemove).ToArray();
}
Here, we use the Where() extension method to keep all elements from the input array that are not equal to the elementToRemove variable.
Subsequently, we convert the resulting sequence of elements back to an integer array using the ToArray() method and we return it.
We remove every instance of the element, with a more concise syntax, using LINQ.
Use Array.FindAll() to Delete Array Elements
Another similar approach is with the static Array.FindAll() method:
public int[] DeleteWithFindAll(int[] inputArray, int elementToRemove)
{
return Array.FindAll(inputArray, i => i != elementToRemove);
}
Here, we use the FindAll() method of the Array class to return all elements from the input array that are not equal to the elementToRemove value.
Use the List RemoveAll() Method
We can achieve the same results for deleting elements from an array by using the RemoveAll() method:
public int[] DeleteWithRemoveAll(int[] inputArray, int elementToRemove)
{
var list = new List<int>(inputArray);
list.RemoveAll(e => e == elementToRemove);
return list.ToArray();
}
First, we create a new List<int>() object from the inputArray array argument.
Then we use the RemoveAll() method of the List<T> class to remove all elements in the list that are equal to the elementToRemove.
Finally, we return the list back to an integer array using again the ToArray() method.Â
Use a For Loop and a List() to Remove Multiple Elements
Here, we can make use of a for loop and a List collection to remove elements:
public int[] DeleteWithList(int[] inputArray, int elementToRemove)
{
var indexToRemove = Array.IndexOf(inputArray, elementToRemove);
if (indexToRemove < 0)
{
return inputArray;
}
var list = new List<int>(inputArray.Length);
for (int i = 0; i < inputArray.Length; i++)
{
if (inputArray[i] != elementToRemove)
{
list.Add(inputArray[i]);
}
}
return list.ToArray();
}
After we check if the element exists in our input source array, we create a new List<int> object with an initial capacity equal to the length of the inputArray.
Then, we use a for loop to iterate through each element of the inputArray. If the examined element is not equal to the elementToRemove, it is added to the list using the List<T>.Add() method.
Finally, we return the new integer array using the List<T>.ToArray() method. The resulting array contains all the elements of the original inputArray except for the elementToRemove.
Use ArrayPool To Remove Multiple Elements
We can take advantage of using the array from the ArrayPool<T> to skip a buffer allocation in comparison with the List option:
using System.Buffers;
public static int[] DeleteWithPooledArray(int[] source, int elementToRemove)
{
var tempArray = ArrayPool<int>.Shared.Rent(source.Length);
try
{
var tempSpan = tempArray.AsSpan();
var index = 0;
foreach (var element in source.AsSpan())
{
if (element != elementToRemove) tempSpan[index++] = element;
}
return tempSpan[0..index].ToArray();
}
finally
{
ArrayPool<int>.Shared.Return(tempArray);
}
}
We can even improve this code by installing the CommunityToolkit.HighPerformance NuGet package, which enables cleaner work with ArrayPool.
A big thanks to Jeff S. who suggested this solution in the comment section.
What’s the Fastest Way to Delete an Element From an Array?
For removing the first instance of a value, the methods built on a block copy are the fastest. In our runs on .NET 11, Array.Copy(), Buffer.BlockCopy(), ArraySegment and the collection expression all finished within a few hundred nanoseconds on a 1,000-element array, close enough that their order changes between runs. The hand-written loop was clearly the slowest of the group. All of them allocate about the same 3.9 KB, the new array of 999 integers.
For removing every instance, the ArrayPool version came first, at a little over a microsecond. Where(), RemoveAll(), FindAll() and the List<T> loop all took longer, from FindAll() at about 1.5 microseconds to the List<T> loop at about 2.4.
So for a single delete, Array.Copy() is a safe default. For removing every match, Where() or FindAll() is the shortest code and the pooled array is the fastest. On arrays this size, the gap is under a microsecond and a half per call, which only matters in a hot path.
Here is every approach from this article side by side:
| Way | Core call | Removes | Changes the input array |
|---|---|---|---|
Array.Copy() | Array.Copy(inputArray, ..., tempArray, ...) twice | First instance | No |
ArraySegment<T> | segment1.Concat(segment2).ToArray() | First instance | No |
for loop | tempArray[j] = inputArray[i] | First instance | No |
for loop and Array.Resize() | Array.Resize(ref inputArray, inputArray.Length - 1) | First instance | Yes, shifts it in place |
Buffer.BlockCopy() | Buffer.BlockCopy(..., n * sizeof(int)) twice | First instance (primitive or enum arrays only) | No |
| Collection expression | [.. span[..index], .. span[(index + 1)..]] | First instance | No |
| Range | inputArray[1..] | The element at index 0 | No |
Where() | inputArray.Where(e => e != x).ToArray() | Every instance | No |
Array.FindAll() | Array.FindAll(inputArray, i => i != x) | Every instance | No |
List<T>.RemoveAll() | list.RemoveAll(e => e == x) | Every instance | No |
for loop and List<T> | list.Add(inputArray[i]) | Every instance | No |
ArrayPool<T> | ArrayPool<int>.Shared.Rent(source.Length) | Every instance | No |
Only the Array.Resize() version touches the array we pass in. Every other method leaves the input as it was and returns a new array. The ones that look up the index first return the input itself when there is nothing to remove.
We will evaluate these methods to find the most efficient one in terms of speed, with the benchmark class. Let’s create a method to use in our benchmark:
private static int[] FillArray()
{
var rnd = new Random(42);
var myArray = new int[1000];
for (int i = 0; i < 1000; i++)
{
myArray[i] = rnd.Next(1, 10);
}
return myArray;
}
Here, we return a random integer array of length 1000 using the .NET Random class, with each element of the array being a random number between 1 and 9. The fixed seed, 42, gives us the same array on every run.
Every benchmark method calls the matching method from our sample with that array and removes the value 7, so the benchmark measures the code we’ve seen above.
Exact timings change from run to run and from machine to machine. First, let’s evaluate the methods that remove only the first instance of the element:
| Method | Mean | Error | StdDev | Rank | Gen0 | Allocated | |------------------------------- |-----------:|---------:|---------:|-----:|-------:|----------:| | DeleteWithArrayCopy | 203.6 ns | 9.88 ns | 28.18 ns | 1 | 0.4809 | 3.93 KB | | DeleteWithArraySegment | 221.1 ns | 8.72 ns | 25.16 ns | 2 | 0.4952 | 4.05 KB | | DeleteWithCollectionExpression | 222.2 ns | 5.69 ns | 16.67 ns | 2 | 0.4809 | 3.93 KB | | DeleteWithBufferCopy | 235.0 ns | 11.23 ns | 32.75 ns | 2 | 0.4809 | 3.93 KB | | DeleteWithLoop | 820.7 ns | 16.34 ns | 39.46 ns | 3 | 0.4807 | 3.93 KB |
We observe that the DeleteWithArrayCopy() method is among the fastest at removing only the first instance of the element. It uses the Array.Copy() method twice to create a new array without the removed element.
This approach avoids looping through the input array and copying elements one by one, which can be slow. It uses a built-in method that can copy large blocks of memory efficiently.Â
Also, the .NET runtime source has a comment right above Buffer.BlockCopy() that advises: “If you want to use traditional array element indices and counts, use Array.Copy.”
So, when we want to remove only one instance of an element from an array, one of the most efficient ways is to use the DeleteWithArrayCopy() method.
Now, let’s benchmark the solutions that remove every instance from the given array:
| Method | Mean | Error | StdDev | Rank | Gen0 | Gen1 | Allocated | |------------------------------- |-----------:|---------:|---------:|-----:|-------:|-------:|----------:| | DeleteWithPooledArray | 1,082.1 ns | 21.29 ns | 21.86 ns | 1 | 0.4349 | - | 3.55 KB | | DeleteWithFindAll | 1,520.5 ns | 28.75 ns | 28.24 ns | 2 | 1.4248 | 0.0095 | 11.64 KB | | DeleteWithRemoveAll | 1,731.2 ns | 24.78 ns | 21.97 ns | 3 | 0.9212 | 0.0057 | 7.54 KB | | DeleteWithWhere | 1,841.7 ns | 36.59 ns | 66.91 ns | 4 | 0.4501 | - | 3.68 KB | | DeleteWithList | 2,366.4 ns | 46.88 ns | 48.15 ns | 5 | 0.9193 | 0.0038 | 7.52 KB |
For deleting multiple elements, the DeleteWithPooledArray() method seems to be the winner.
The Where(), FindAll() and RemoveAll() versions take a lambda expression and call a delegate for every element to decide whether to keep it, which adds some overhead compared to the pooled array’s plain loop. Only Where() is LINQ, though: FindAll() is a static method of Array, and RemoveAll() belongs to List<T>. The Allocated column also shows that FindAll(), RemoveAll() and the List<T> loop allocate between two and three and a half times as much memory as the pooled array.
Conclusion
In this article, we looked at several different methods that allow us to delete elements from an array. Then, we evaluated our solutions in terms of performance and efficiency, determining which was the best choice to suit our requirements.
If we need to remove elements often, a List<T> is the better container from the start, and our article on removing elements from a list while iterating covers what goes wrong when we do that inside a loop.
Tested with .NET 11.0.0, BenchmarkDotNet 0.15.8 and MSTest 4.5.3.






