I have a List
of cards called _deck:
private List<String> _deck = new List<String> {"2h", "3h", "4h", ... }
And then I want to remove a card from the List
and save into a variable. I'm trying to do:
String p1FirstCard = _deck.RemoveAt(0);
but I'm getting the error
Cannot convert type void to String
In C# List
is there something like push/pop but which does that at the "head" or "start" of the List
? (Push/pop works at the "tail" or "end" of the list.)
If not, how should I do remove the first element but save it in a variable?
To pop the first element in the list, use the RemoveAt() method. It eliminates the element from the position you want to remove the element. myList. RemoveAt(0);
The Dequeue method is used to dequeue the first string. The Peek method is used to look at the next item in the queue, and then the Dequeue method is used to dequeue it.
A Queue in C# represents a first-in, first-out (FIFO) collection of objects. An example of a queue is a line of people waiting. The Queue<T> class in the System. Collection. Generic namespace represents a queue in C#, where T specifies the type of elements in the queue.
If you want to dequeue the first element, you could simply use a Queue<T>
.
class Program { static void Main(string[] args) { var _deck = new Queue<String>(); _deck.Enqueue("2h"); _deck.Enqueue("3h"); _deck.Enqueue("4h"); _deck.Enqueue("..."); var first = _deck.Dequeue(); // 2h first = _deck.Dequeue(); // 3h } }
If you want to pop the last element, you could use a Stack<T>
.
class Program { static void Main(string[] args) { var _deck = new Stack<String>(); _deck.Push("2h"); _deck.Push("3h"); _deck.Push("4h"); _deck.Push("..."); var first = _deck.Pop(); // ... first = _deck.Pop(); // 4h } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With