Can I directly "Extract" an Item from a List<>?

.net, c#, linq, list

Solution

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`.

Problem

I have a List of 5 items. I want to extract the last item, like : ``` string lastItem = myList.Last(); ``` but after this, myList must contain 4 items, everythings except the last one, which is just extracted. Is it possible? Or I need to use .Take(4)?

Original source