Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 reasons I cannot use the Stack class.

Thanks

Francesco

like image 689
CiccioMiami Avatar asked Nov 17 '25 13:11

CiccioMiami


2 Answers

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?

like image 55
James Michael Hare Avatar answered Nov 19 '25 01:11

James Michael Hare


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

like image 40
Adam Robinson Avatar answered Nov 19 '25 01:11

Adam Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!