Deleting a specific item of an array

25,178

Solution 1

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);

Solution 2

You cannot delete items in an array, because the length of a C# array is fixed at the time when it is created, and cannot be changed after that.

You can null out the corresponding element to get rid of the string, or use LINQ to produce a new array, like this:

columns = columns.Take(MY_INT_HERE-1).Concat(columns.Skip(MY_INT_HERE)).ToArray();

You need to add using System.Linq at the top of your C# file in order for this to compile.

However, using a List<string> would be a better solution:

List<string> columns;
columns.RemoveAt(MY_INT_HERE);

Solution 3

If you don't want to use linq you can use this function :

public string[] RemoveAt(string[] stringArray, int index)
{
  if (index < 0 || index >= stringArray.Length)
    return stringArray;
  var newArray = new string[stringArray.Length - 1];
  int j = 0;
  for (int i = 0; i < stringArray.Length; i++)
  {
    if(i == index)continue;
    newArray[j] = stringArray[i];
    j++;
  }
  return newArray;
}

You use it like that : columns = RemoveAt(columns, MY_INT_HERE)

You can also make it to an extension method.

Share:
25,178
Anoushka Seechurn
Author by

Anoushka Seechurn

Updated on April 05, 2020

Comments

  • Anoushka Seechurn
    Anoushka Seechurn about 4 years
    string[] columns
    

    I want to delete the item on an index specified by a variable of type int.

    How do I do this ?

    I tried

    columns.RemoveAt(MY_INT_HERE);
    

    But apparently this does not works.