开发者

Is there any method or way in C# to add items in a List<T> on a LIFO basis?

开发者 https://www.devze.com 2023-02-28 11:34 出处:网络
this is an easy one. I have a List<T> in C# and I woudl like to add some elements on a LIFO basis, so on the \"bottom\" of the List<T>.

this is an easy one. I have a List<T> in C# and I woudl like to add some elements on a LIFO basis, so on the "bottom" of the List<T>. For several r开发者_如何学Pythoneasons I cannot use the Stack class.

Thanks

Francesco


Yes the Add() method adds to the end of the list, you can use RemoveAt(yourList.Count - 1) to remove last, and yourList[yourList.Count - 1] to peek at the last.

Though I'm curious, why can't you use the Stack() class?


Items added to a List<T> using the Add method are placed at the end of the list. If you want to process the list so that it's LIFO, either iterate in reverse (meaning you change the way you process the list) or always use Insert(0, item) to add elements to the list (meaning you change the way you populate the list).


You can insert anywhere in the list you'd like.

http://msdn.microsoft.com/en-us/library/sey5k5z4.aspx


Insert(0,T)

http://msdn.microsoft.com/en-us/library/sey5k5z4.aspx

This isn't a stack though. If you want to remove objects again as you use them, I'd consider extending a stack...


LIFO and FIFO is not a question of adding but a question of removing.

You can use List<T> and always pick up the last item:

List<int> list = Enumerable.Range(1,100).ToList();
While(list.Count>0)
{
    list.RemoveAt(list.Count-1);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号