Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove a number in array?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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); 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading