Razzor
Razzor

Reputation: 63

Moving all items in array one place back

I have an array:

string[] inventory = { "empty", "empty", "empty", "empty", "empty"}

Later in code, by collecting items "in game", these empty items will change to "item name". Then, user can use them or remove them from inventory. When user removes some item, i need to move all following items in array one place back. Etc.:

Inventory contains items "a" "b" "c" "d" "empty":

string[] inventory = { "a", "b", "c", "d" "empty" };

When user removes item "a", items "b" "c" "d" and "empty" must go one place back in array, so new array will be:

inventory = { "b", "c", "d", "empty", "empty" };

One way to do this could be to save all other items in array to another array and then manually redeclare inventory with changed "position" in array. But what if I have inventory[100] ... is there any other way to do this, without that long redeclaring?

Thank you for help.

Upvotes: 1

Views: 259

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

You can create Inventory class which will keep items and act as items enumerator (it will add empty items for enumeration but will not keep them in memory):

public class Inventory : IEnumerable<string>
{
    private readonly int size;
    private const string emptyItem = "empty";
    private List<string> items = new List<string>();

    public Inventory(int size)
    {
        this.size = size;
    }

    public void Add(string item)
    {
        if (items.Count == size)
            throw new Exception("Inventory is full");

        items.Add(item);
    }

    public void Remove(string item)
    {
        items.Remove(item);
    }

    public IEnumerator<string> GetEnumerator()
    {
        return items.Concat(Enumerable.Repeat(emptyItem, size - items.Count))
                    .GetEnumerator();
    }

    IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Usage:

Inventory inventory = new Inventory(5);            
inventory.Add("a");
inventory.Add("b");
inventory.Remove("a"); 
var result = String.Join(", ", inventory);

Result:

b, empty, empty, empty, empty

Upvotes: 2

Roman
Roman

Reputation: 1877

You can use List<string> for that. You won't have a limit of elements. Once you remove one element, other will be kept in order and you don't have to do any reshuffling.

Upvotes: 0

Related Questions