Question

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?

Was it helpful?

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?

OTHER TIPS

A list is an array behind the scenes (if you use some IL disassembler like Reflector you'll be able to check this).

Having said that, when you remove an item from a list, the List<T> will create a new array internally from the source one having all items excepting the removed one.

In the other hand, when you insert an item to the list, you replace the item in the whole index and everything from the index down is moved down one position (thanks to BinaryWorrier). The object that was in the index won't be "destroyed": you're removing an object reference from the list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top