Home > Enterprise >  How to remove a number in array?
How to remove a number in array?

Time:09-11

First declaration a arr:

 int[] arr1 = { 1, 2, 3, 4 };

Second:

 arr1[3] = default(int);

do this aim for remove a num in this arr. but i can find this number using index 3,why? Since I've already deleted this element, why can I still access this element while traversing the group?

CodePudding user response:

Technically, you can remove item at index index by shift and Array.Resize:

      int[] arr1 = { 1, 2, 3, 4 };

      int index = 3;

      // Let it be a good old for loop; alternative is
      // Array.Copy(arr1, index   1, arr1, index, arr1.Length - index - 1);
      for (int i = index; i < arr1.Length - 1;   i)
        arr1[i] = arr1[i   1];

      Array.Resize(ref arr1, arr1.Length - 1);

However, you can switch from array int[] to List<int> an call RemoveAt:

      var arr1 = new List<int>() { 1, 2, 3, 4 };

      int index = 3;

      arr1.RemoveAt(index); 
  • Related