score:4

Accepted answer

you can use list.remove, list.removerange or list.removeat methods to remove elements from the list.

to remove the last element of the list after you obtained a reference to it using the list indexer you use:

var element = mylist[mylist.count - 1];
mylist.removeat(mylist.count - 1);

using removeat instead of remove is more efficient because there is no need to first find the index of the item to be removed and also to note that remove just removes the first occurrence that matches the item to be removed, so in a list with duplicates it will not be the last element.

finally, if you have an algorithm where will be removing the last item of a list several times, you might as well consider another data structure, like for example a queue.

score:1

why not use a stack instead of a list it seems more appropriate

[test]
public void mytest()
{
    stack<int> stack = new stack<int>(new[] { 1, 2, 3, 4, 5 });
    int pop = stack.pop();
    assert.areequal(stack.count, 4);
    assert.areequal(pop, 5);
}

score:2

create an extension method to do this

public static class extension
{
  public static string removelast(this ilist<string> mylist)
  {
     int lastitemindex = mylist.count - 1;
     string lastitem = mylist.last();
     mylist.removeat(lastitemindex);
     return lastitem; 
  }
}

call it as

string itemremoved = lst.removelast(); //this will delete the last element from list & return last element as well 

score:4

you can create an extension method that takes any index to do the fetch/removal:

public static t extract<t>(this list<t> list, int index)
{
    var item = list[index];
    list.removeat(index);
    return item;
}

the last item can always be found using count - 1, so the call is simply:

var item = list.extract(list.count - 1);

it then means you can "extract" any item by index.

score:5

you can do as following if you want to take the last.

string lastitem = mylist.last();
mylist.remove(mylist.last());
//mylist.count() will now be 4.

Related Query

More Query from same tag