0

How to remove item from a simple array once? For example, a char array contains these letters:

a,b,d,a

I would like to remove the letter "a" one time, then the result would be:

a,b,d
user2843341
  • 283
  • 2
  • 3
  • 8

4 Answers4

2

Removing an item from an array is not really possible. The size of an array is immutable once allocated. There is no way to remove an element per say. You can overwrite / clear an element but the size of the array won't change.

If you want to actually remove an element and change the size of the collection then you should use List<char> instead of char[]. Then you can use the RemoveAt API

List<char> list = ...;
list.RemoveAt(3);
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

If your goal is to just skip the first 'a', then remove the second, you could use something like:

int first = Array.IndexOf(theArray, 'a');
if (first != -1)
{
    int second = Array.IndexOf(theArray, 'a', first+1);
    if (second != -1)
    {
    theArray = theArray.Take(second - 1).Concat(theArray.Skip(second+1)).ToArray();
    }
}

If you just need to remove any of the 'a' characters (since you specified that the order is not relevant), you could use:

int index = Array.IndexOf(theArray, 'a');
if (index != -1)
{
    theArray = theArray.Take(index - 1).Concat(theArray.Skip(index+1)).ToArray();
}

Note that these don't actually remove the item from the array - they create a new array with that element missing from the newly created array. Since arrays are not designed to change in total length once created, this is typically the best alternative.

If you will be doing this frequently, you may want to use a collection type that does allow simple removal of elements. Switching from an array to a List<char>, for example, makes removal far simpler, as List<T> supports simple APIs such as use List<T>.Remove directly.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0

You can use linq by trying the following

var someArray= new string[3];
someArray[0] = "a";
someArray[1] = "b";
someArray[2] = "c";

someArray= someArray.Where(sa => !sa.Equals("a")).ToArray();

Please note: This method is not removing the element from the array but that it is creating a new array that is excluding the element. This may have an effect on performance.

You might consider using a list or collection.

Andre Lombaard
  • 6,985
  • 13
  • 55
  • 96
0
static void Main(string[] args)
{
    char[] arr = "aababde".ToArray();
    arr = RemoveCharacter(arr, 'a');
    arr = RemoveCharacter(arr, 'b');
    arr = RemoveCharacter(arr, 'd');
    arr = RemoveCharacter(arr, 'z');
    arr = RemoveCharacter(arr, 'a');
    //result is 'a' 'b' 'e'
}

static char[] RemoveCharacter(char[] array, char c)
{
    List<char> list = array.ToList();
    list.Remove(c);
    return list.ToArray();
}
Weyland Yutani
  • 4,682
  • 1
  • 22
  • 28