How to remove an empty item from List?

Hello i have this methods in my script

This method adds item to list:

public void Equip(Equipment newItem, ItemType2 itemType)
{
    Equipment oldItem = null;
    if (itemType == ItemType2.laser)
    {
        //addToArray(newItem);
        lasers.Add(newItem);
        //Debug.Log("Laser added");
    }
    if (itemType == ItemType2.engine)
    {
        engines.Add(newItem);
        //Debug.Log("Engine added");
    }
    if (onEquipmentChanged != null)
    {
        onEquipmentChanged.Invoke(newItem, oldItem);
    }
}

This method removes item from list:

public void UnequipLasers(int slotIndex)
{
    if (lasers[slotIndex] != null)
    {
        Equipment oldItem = lasers[slotIndex];
        inventory.Add(oldItem);
        lasers[slotIndex] = null;
        //lasers.RemoveAll(x => !x);
        lasers.Remove(null);
        if (onEquipmentChanged != null)
        {
            onEquipmentChanged.Invoke(null, oldItem);
        }
    }
}

This method removes all items from lists:

public void UnequipAll()
{
        for (int i = 0; i < lasers.Count; i++)
        {
            UnequipLasers(i);
            //lasers.RemoveAll(x => !x);
        }
        for (int i = 0; i < engines.Count; i++)
        {
            UnequipEngines(i);
        }
}

But i want to delete empty item from list, after i removed item

If i use

lasers.Remove(null);

in 2nd method then my 3rd method doesn’t remove all items, it removes only 1 item at time
How do i fix this ?

This is how you do it:

lasers.RemoveAt( slotIndex );

And if you need to remove items while iterating over a list, then do it in reverse order like this:

for( int i=list.Count-1 ; i!=-1  ; i-- )
{
    list.RemoveAt( i );
}

I have empty list at start
Capture
Then i add 3 items
Capture1
Then i try UneqipAll() with RemoveAt in UnequipLasers()
Capture2
And it removes 2 items, but 1 item still in list

This is exactly what happen when you iterate forward (!) from 0 to list.Count

This is what happens in steps:

  1. 0 / 3
  2. 1 / 2
  3. 2 / 1 - loop stops here since 2<1 is false

(index / count)

This is how you’re left with 1 item.