216

Lets say I have this array,

int[] numbers = {1, 3, 4, 9, 2}; 

How can I delete an element by "name"? , lets say number 4?

Even ArrayList didn't help to delete?

string strNumbers = " 1, 3, 4, 9, 2"; ArrayList numbers = new ArrayList(strNumbers.Split(new char[] { ',' })); numbers.RemoveAt(numbers.IndexOf(4)); foreach (var n in numbers) { Response.Write(n); } 
6
  • What if you have duplicate values in your list? Do you want just to remove the first instance or all of the instances? Commented Jan 30, 2009 at 19:48
  • yes, I don't have duplicate values, any idea? Commented Jan 30, 2009 at 19:59
  • ahmed Do you mean, No you do not, or yes you do? (not insulting your english, just asking for clarification) Commented Jan 30, 2009 at 20:14
  • @Malfist - sorry :), I meant I don't care about duplicated values because I am sure there are not any of them in my case, thanks again Commented Jan 30, 2009 at 20:33
  • 6
    You cannot remove items from arrays in C#, as you can see from this example program. What you can do is create a new array, copy only some of the elements of the original one and assign it back to the original variable. This is what is done in all the answers. Commented Feb 5, 2014 at 13:37

13 Answers 13

445

If you want to remove all instances of 4 without needing to know the index:

LINQ: (.NET Framework 3.5)

int[] numbers = { 1, 3, 4, 9, 2 }; int numToRemove = 4; numbers = numbers.Where(val => val != numToRemove).ToArray(); 

Non-LINQ: (.NET Framework 2.0)

static bool isNotFour(int n) { return n != 4; } int[] numbers = { 1, 3, 4, 9, 2 }; numbers = Array.FindAll(numbers, isNotFour).ToArray(); 

If you want to remove just the first instance:

LINQ: (.NET Framework 3.5)

int[] numbers = { 1, 3, 4, 9, 2, 4 }; int numToRemove = 4; int numIndex = Array.IndexOf(numbers, numToRemove); numbers = numbers.Where((val, idx) => idx != numIndex).ToArray(); 

Non-LINQ: (.NET Framework 2.0)

int[] numbers = { 1, 3, 4, 9, 2, 4 }; int numToRemove = 4; int numIdx = Array.IndexOf(numbers, numToRemove); List<int> tmp = new List<int>(numbers); tmp.RemoveAt(numIdx); numbers = tmp.ToArray(); 

Edit: Just in case you hadn't already figured it out, as Malfist pointed out, you need to be targetting the .NET Framework 3.5 in order for the LINQ code examples to work. If you're targetting 2.0 you need to reference the Non-LINQ examples.

Sign up to request clarification or add additional context in comments.

Comments

46
int[] numbers = { 1, 3, 4, 9, 2 }; numbers = numbers.Except(new int[]{4}).ToArray(); 

1 Comment

Consider adding some form of an explanation as to why this solves the problem and how it effectively differs from the accepted answer (or any of the other answers for that matter)
35

You can also convert your array to a list and call remove on the list. You can then convert back to your array.

int[] numbers = {1, 3, 4, 9, 2}; var numbersList = numbers.ToList(); numbersList.Remove(4); 

2 Comments

numbersList.Remove(4); has to be: numbersList.RemoveAt(4);
@Deniz *Yoda voice* Closer look, my friend. To the array there is more than you see. Valid both are, numbersList.Remove(4) and numbersList.RemoveAt(4)! But the same result, they do not give.
12

The code that is written in the question has a bug in it

Your arraylist contains strings of " 1" " 3" " 4" " 9" and " 2" (note the spaces)

So IndexOf(4) will find nothing because 4 is an int, and even "tostring" would convert it to of "4" and not " 4", and nothing will get removed.

An arraylist is the correct way to go to do what you want.

2 Comments

List<T> would be better than ArrayList.
This answer deserves more upvotes. While I absolutely agree with @MikeScott that List<T> would be better than ArrayList, this seems to be the only answer that correctly identifies the problem that the OP had when he tried to use ArrayList to solve his original problem. The OP understood that you can't resize arrays, which nobody else seems to have noticed, and tried to use a resizeable type instead, which nobody else seems to have noticed, and then got tripped up by a different problem, which nobody else seems to have noticed.
10

I posted my solution here.

This is a way to delete an array element without copying to another array - just in frame of the same array instance:

 public static void RemoveAt<T>(ref T[] arr, int index) { for (int a = index; a < arr.Length - 1; a++) { // moving elements downwards, to fill the gap at [index] arr[a] = arr[a + 1]; } // finally, let's decrement Array's size by one Array.Resize(ref arr, arr.Length - 1); } 

1 Comment

Resize actually copies the data to a new array (unless the passed new size is the length of the passed array); it doesn't change the size of the passed array instance. That's why it's a reference parameter. See referencesource.microsoft.com/mscorlib/R/71074deaf111c4e3.html.
7

Removing from an array itself is not simple, as you then have to deal with resizing. This is one of the great advantages of using something like a List<int> instead. It provides Remove/RemoveAt in 2.0, and lots of LINQ extensions for 3.0.

If you can, refactor to use a List<> or similar.

2 Comments

I think it's the best solution in this case.
It is a duplicate of Dave Dp answer stackoverflow.com/a/4493444/52277
6

Balabaster's answer is correct if you want to remove all instances of the element. If you want to remove only the first one, you would do something like this:

int[] numbers = { 1, 3, 4, 9, 2, 4 }; int numToRemove = 4; int firstFoundIndex = Array.IndexOf(numbers, numToRemove); if (numbers >= 0) { numbers = numbers.Take(firstFoundIndex).Concat(numbers.Skip(firstFoundIndex + 1)).ToArray(); } 

Comments

5

As a generic extension, 2.0-compatible:

using System.Collections.Generic; public static class Extensions { //========================================================================= // Removes all instances of [itemToRemove] from array [original] // Returns the new array, without modifying [original] directly // .Net2.0-compatible public static T[] RemoveFromArray<T> (this T[] original, T itemToRemove) { int numIdx = System.Array.IndexOf(original, itemToRemove); if (numIdx == -1) return original; List<T> tmp = new List<T>(original); tmp.RemoveAt(numIdx); return tmp.ToArray(); } } 

Usage:

int[] numbers = {1, 3, 4, 9, 2}; numbers = numbers.RemoveFromArray(4); 

1 Comment

The documentation text does not match the implementation: The implementation only removes the first instance, but the documentation says all instances of itemToRemove. The documentation says a new array is returned, but when there is no element to remove, the original array is returned instead of a new one, which might lead to inconsistencies if the result gets modified.
2

You can do in this way:

int[] numbers= {1,3,4,9,2}; List<int> lst_numbers = new List<int>(numbers); int required_number = 4; int i = 0; foreach (int number in lst_numbers) { if(number == required_number) { break; } i++; } lst_numbers.RemoveAt(i); numbers = lst_numbers.ToArray(); 

Comments

1

' To remove items from string based on Dictionary key values. ' VB.net code

 Dim stringArr As String() = "file1,file2,file3,file4,file5,file6".Split(","c) Dim test As Dictionary(Of String, String) = New Dictionary(Of String, String) test.Add("file3", "description") test.Add("file5", "description") stringArr = stringArr.Except(test.Keys).ToArray() 

Comments

1

In recent C#/.NET featuring the Span<T> type and range expressions this can be done using the Span.CopyTo method to move array elements around:

// Removes a[i..i+n], fast but not preserving the order of array elements. void arrayRemoveAtFast<T>(ref T[] a, int i, int n) { // Create a Span that references the array elements. var s = a.AsSpan(); // Copy the last n array elements to positions i…i+n. // Caveat: Use `s`, not `a`, or else the result may be invalid. s[^n..].CopyTo(s[i..(i+n)]); // Cut the last n array elements off. a = a[..^n]; } // Removes a[i..i+n], preserving the order of array elements. void arrayRemoveAtPreserveOrder<T>(ref T[] a, int i, int n) { // Create a Span that references the array elements. var s = a.AsSpan(); // Move array elements that follow the ones to remove to the front. // Caveat: Use `s`, not `a`, or else the result may be invalid. s[(i + n)..].CopyTo(s[i..^n]); // Cut the last n array elements off. a = a[..^n]; } 

Comments

0
 public int[] DeletePart(int position, params int[] numbers) { int[] result = new int[numbers.Length - 1]; int z=0; for (int i = 0; i < numbers.Length; i++) { if (position - 1 != i) { result[z] = numbers[i]; z++; } } return result; } 

Comments

-6

We can delete array elements by using for loops and continue statements:

string[] cars = {"volvo", "benz", "ford", "bmw"}; for (int i = 0; i < cars.Length; i++) { if (cars[i] == "benz") { continue; } Console.WriteLine(cars[i]); } 

3 Comments

That does not change the array in anyway.
This removes an element from an array in the same way that covering up your eyes removes a baby from the room.
delete an element that we won't display in output. your right, that doesnt change the array in reality.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.