Search code examples
c#listinsertinventory

Do I use insert in a list or is there another way C#


I am making an inventory system but I cant remember which I can use.

I have a mouse list<item> and inventory<item> if a button is clicked I want to remove the item from the inventory and move it to mouse, (which I have done) but then to place it back somewhere is where I have the trouble.

It would be simple if there isnt already an item there ... i.e just use insert but if there is an item there what do i do? Do I add it to the mouse list then insert at the position or does insert move the old list item to the beginning or the end or the next one in the list. Or, is there another way?

Basically I want to click on a button remove the item thats already there and put in the item thats in the mouse list , then if there is already something in the mouse list add that to where the old item used to be.

Im wondering how does insert work with lists.

What happens to the object/item that is already at that index if I insert it at index 2 does the object/item already there move up and become index 3 or does it get deleted.

I want to know if I remove something from the list does that index become null? , i.e if its like this index 0 = 2 index 1 = 51 index 2 = 213 index 3 = null index 4= 234 for example or does index 4 become index 3?


Solution

  • Lets have a look and see

    static void Main(string[] args)
    {
        var names = new List<string> { "Homer", "Marge", "Lisa" };
    
        Show(names);
    
        names.Insert(1, "Bart");
        Console.WriteLine("Inserted Bart at 1");
    
        Show(names);
    
        names.RemoveAt(0);
        Console.WriteLine("Removed Homer");
        Show(names);
    }
    
    private static void Show(List<string> names)
    {
        Console.WriteLine("Names");
        for (int i = 0; i < names.Count; i++)
            Console.WriteLine("\t{0}: {1}", i, names[i]);
    }
    

    Gives us . . .

    Names
    0: Homer
    1: Marge
    2: Lisa
    Inserted Bart at 1
    Names
    0: Homer
    1: Bart
    2: Marge
    3: Lisa
    Removed Homer
    Names
    0: Bart
    1: Marge
    2: Lisa

    So.

    1. Adding at the second position, will move the previous second item down to the third item (and pushing everything below that down one position too)
    2. Removing an item moves everything up by one item

    The scientific method helps with questions like these (i.e. theorise, experiment, observe, repeat as necessary)

    Does this answer your question?