How to delete/remove an element from a C# array?



To delete an elements from a C# array, we will shift the elements from the position the user want the element to delete.

Here, first we have 5 elements −

int[] arr = new int[5] {35, 50, 55, 77, 98};

Now let’s say we need to delete the element at 2nd position i.e. variable “pos = 2” is set, for that shift the elements after the specified position −

// Shifting elements for (i = pos-1; i < 4; i++) {    arr[i] = arr[i + 1]; }

Now display the result as shown in the complete code below.

Example

 Live Demo

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo {    class Program {       static void Main() {          int i = 0;          int pos;          int[] arr = new int[5] {35, 50, 55, 77, 98};          Console.WriteLine("Elements before deletion:");          for (i = 0; i < 5; i++) {             Console.WriteLine("Element[" + (i) + "]: "+arr[i]);          }          // Let's say the position to delete the item is 2 i.e. arr[1]          pos = 2;          // Shifting elements          for (i = pos-1; i < 4; i++) {             arr[i] = arr[i + 1];          }          Console.WriteLine("Elements after deletion: ");          for (i = 0; i < 4; i++) {             Console.WriteLine("Element[" + (i + 1) + "]: "+arr[i]);          }          Console.WriteLine();       }    } }

Output

Elements before deletion: Element[0]: 35 Element[1]: 50 Element[2]: 55 Element[3]: 77 Element[4]: 98 Elements after deletion: Element[1]: 35 Element[2]: 55 Element[3]: 77 Element[4]: 98
Updated on: 2020-06-20T16:06:09+05:30

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements