Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "Dequeue" Element from a List?

Tags:

arrays

c#

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?

like image 821
Mc' Flips Avatar asked Jul 20 '14 23:07

Mc' Flips


People also ask

How to pop element from list in c#?

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);

What does dequeue method do?

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.

What is queue in C# with example?

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.


Video Answer


1 Answers

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     } } 
like image 97
Fredou Avatar answered Sep 28 '22 02:09

Fredou