tags:

views:

6260

answers:

4

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);
    }
A: 

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 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.

ctacke
+24  A: 

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)

int[] numbers = { 1, 3, 4, 9, 2 };
int numToRemove = 4;
numbers = Array.FindAll(numbers, val => val != numToRemove).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.

BenAlabaster
This is a better solution than mine.
Malfist
thanks, amazing it works fine :)
ahmed
Linq is .NET 3.5 only, make sure you're project is using it.
Malfist
Thanks for pointing that out, I guess I should've mentioned that you need to be targetting 3.5 to use the LINQ versions...
BenAlabaster
+1  A: 

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();
}
Vojislav Stojkovic
+1  A: 

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.

List<T> would be better than ArrayList.
Mike Scott
I agree actually.