Is there a way to get the last element in a Queue?

前端 未结 5 1465
鱼传尺愫
鱼传尺愫 2021-01-26 18:26

I know stack is best and easiest way, yet could it be possible to obtain the last element in a queue without having to dequeue anything?

5条回答
  •  忘了有多久
    2021-01-26 19:13

    You could use LINQ's Enumerable.Last() method (where myQueue is the name of your Queue):

    var lastElement = myQueue.Last();
    

    Although as others have mentioned, if you find yourself needing to do this often, you probably want to think about using a different data structure. For example, a List:

    var myElement = myList[myList.Length - 1];
    

提交回复
热议问题