0

I'm required to use an array for this specific project. Currently there are names saved at each index in array[10]. What I want to do is if I delete array[1], all data will move up one index freeing up or making array[10] = null. Currently, I'm doing it with

public void Delete(int a)
{
    do
    {
        array[a] = array[a + 1];
    }
    while (array[a + 1] != null);
}

yet when I try to retrieve the array with

for (int h = 0; h < array.Length; h++)
{
    Console.WriteLine(array[h]);
}

there would be a gap in which 1, 3, 4...

Is there a better way to go about it?

WeiJun
  • 51
  • 10
polors2
  • 37
  • 2
  • 8
  • Yes. Try List. You can refer : https://stackoverflow.com/questions/1582285/how-to-remove-elements-from-a-generic-list-while-iterating-over-it – Alden Ken Nov 07 '17 at 03:08
  • @AldenKen I'd love to, but I'm required arrays for this project. – polors2 Nov 07 '17 at 03:10
  • Please edit your question giving a short, but complete, program that can be compiled showing how you are are initializing an array, deleting a value, and printing the results. – astidham2003 Nov 07 '17 at 03:16
  • @polors2 Sorry that i didn't see your question clearly. Try assign your array item that doesn't need to delete to a temperaly array first and then reassign to your array again. Refer: https://stackoverflow.com/questions/457453/remove-element-of-a-regular-array – Alden Ken Nov 07 '17 at 03:17
  • Can you edit the for loop in the code. It is printing only h, probably it should be `Console.WriteLine(array[h]);`. Please confirm. – Mukul Varshney Nov 07 '17 at 03:35

2 Answers2

0

When you delete an item, everything after that item's index will need to shift one to the left. Everything before it will stay intact. Therefore, we need to always start at that index and not bother with indices before it. Here is how:

public static void Delete(int index)
{
    if (index >= array.Length)
    {
        return;
    }
    if (index == array.Length - 1)
    {
        array[index] = null;
        return;
    }
    for (int i = index; i < array.Length - 1; i++)
    {
        array[i] = array[i + 1];
    }
    array[array.Length - 1] = null;
}

<== Fiddle Me ==>

CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
0

You need to resize your array after removing element at specified index. You can call Array.Resize after performing your remove operation.

You can resizing in following way :

    public static void Delete(int a)
    {   
        int resizedArrayLength = array.Length - 1;
        while(a < resizedArrayLength)
        {
            array[a] = array[a + 1];
            a++;
        }
        Array.Resize(ref array, resizedArrayLength); // this will resize your array to specified length.
    }
Akash KC
  • 16,057
  • 6
  • 39
  • 59