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);
}
As a generic extension, 2.0-compatible:
Usage:
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.
If you want to remove all instances of 4 without needing to know the index:
LINQ: (.NET Framework 3.5)
Non-LINQ: (.NET Framework 2.0)
If you want to remove just the first instance:
LINQ: (.NET Framework 3.5)
Non-LINQ: (.NET Framework 2.0)
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.
' To remove items from string based on Dictionary key values. ' VB.net code
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 providesRemove
/RemoveAt
in 2.0, and lots of LINQ extensions for 3.0.If you can, refactor to use a
List<>
or similar.