How to Delete an Element from an Array in C#

How to delete an element from an array in C#

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.

Remove element of a regular array

If you don't want to use List:

var foos = new List<Foo>(array);
foos.RemoveAt(index);
return foos.ToArray();

You could try this extension method that I haven't actually tested:

public static T[] RemoveAt<T>(this T[] source, int index)
{
T[] dest = new T[source.Length - 1];
if( index > 0 )
Array.Copy(source, 0, dest, 0, index);

if( index < source.Length - 1 )
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);

return dest;
}

And use it like:

Foo[] bar = GetFoos();
bar = bar.RemoveAt(2);

Remove element of Array (c#)


List<string> wordBank = new List<string>  {
"iphone", "airpods", "laptop","computer","calculator","ram","graphics", "cable","internet","world wide web"
};

//select random word
Random wordRand = new Random();
int index = wordRand.Next(wordBank.Count);
string wordSelect = wordBank[index];

wordBank.RemoveAt(index);
//or
wordBank.Remove(wordSelect);

How to delete a chosen element in array?

I'm assuming you are working with a basic array of strings:

var strItems = new string[] { "1", "2", "3", "4", "5" };

In .NET, that array is always going to be 5 elements long. In order to remove an element, you are going to have to copy the remaining elements to a new array and return it. Setting the value at a position to null does not remove it from the array.

Now, with things like LINQ this is very easy (not shown here), or you could cheat using the List<> collection and do this:

var list = new List<string>(strItems);
list.Remove("3");
strItems = list.ToArray();

But I don't think that's going to teach you anything.

The first step is to find the index of the element you wish to remove. You can use Array.IndexOf to help you out. Let's find the middle element, "3":

int removeIndex = Array.IndexOf(strItems, "3");

If the element was not found, it will return a -1, so check for that before doing anything.

if (removeIndex >= 0)
{
// continue...
}

Finally you have to copy the elements (except the one at the index we don't want) to a new array. So, altogether, you end up with something like this (commented for explanation):

string strInput = Console.ReadLine();
string[] strItems = new string[] { "1", "2", "3", "4", "5" };

int removeIndex = Array.IndexOf(strItems, strInput);

if (removeIndex >= 0)
{
// declare and define a new array one element shorter than the old array
string[] newStrItems = new string[strItems.Length - 1];

// loop from 0 to the length of the new array, with i being the position
// in the new array, and j being the position in the old array
for (int i = 0, j = 0; i < newStrItems.Length; i++, j++)
{
// if the index equals the one we want to remove, bump
// j up by one to "skip" the value in the original array
if (i == removeIndex)
{
j++;
}

// assign the good element from the original array to the
// new array at the appropriate position
newStrItems[i] = strItems[j];
}

// overwrite the old array with the new one
strItems = newStrItems;
}

And now strItems will be the new array, minus the value specified for removal.

C# Adding and Removing elements to an array with an existing size

You can't do that with arrays in C# without allocating a new array. Because arrays are fixed in size.

If you want to be able to add/remove elements from a container, you could use List<T>. Alternativly you could use an ArrayList but that is not recommended, since in most cases List<T> has a performance advantage.

Internally both use an array as the default container for your data. They also take care of resizing the container according to how much data you put in the collection or take out.

In your example, you would use a list like

 List<string> food = new List<string> { "Bacon", "Cheese", "Patty", "Crabs" };

food.Add("Milk"); //Will add Milk to the list
food.Remove("Bacon"); //Will remove "Bacon"

List on MSDN: Docs

Deleting a specific item of an array

Array is immutable class, you can't change it, all you can do is to re-create it:

List<String> list = columns.ToList(); // <- to List which is mutable
list.RemoveAt(MY_INT_HERE); // <- remove
string[] columns = list.ToArray(); // <- back to array

May be the best solution is to redesign your code: change immutable array into List<String>:

  List<String> columns = ...
columns.RemoveAt(MY_INT_HERE);

Delete a number from Array in C#

If you don't want to print 0 I don't know why you're adding it in the first place, but notice the two different ways you "print" the array.

The first method (the print function) starts at item 1 (skipping the "first" element at index 0) and loops until the end.

The second just joins all elements (including the "first" element) of the array and prints the resulting string.

So how do you skip the zero? There are many ways:

  • Don't add zero in the first place (and change your print loop to start at 0)

  • Use the same print method that loops from 1

  • Skip the first item in your array:

    Console.WriteLine(String.Join(", ", a.Skip(1)));

Personally, I would just use the same method for printing both times, and I would also use Array.RemoveAt to "delete" the item rather then creating a new array by using Where().ToArray().



Related Topics



Leave a reply



Submit