text stringlengths 0 13.4k |
|---|
There is a collection in .Net used to manage values in a Stack that uses the LIFO (last-in first-out) concept. The |
basics of stacks is the method Push(T item) which is used to add elements in the stack and Pop() which is used to |
get the last element added and remove it from the stack. The generic version can be used like the following code |
for a queue of strings. |
First, add the namespace: |
using System.Collections.Generic; |
and use it: |
Stack<string> stack = new Stack<string>(); |
stack.Push("John"); |
stack.Push("Paul"); |
stack.Push("George"); |
stack.Push("Ringo"); |
string value; |
value = stack.Pop(); // return Ringo |
value = stack.Pop(); // return George |
value = stack.Pop(); // return Paul |
value = stack.Pop(); // return John |
There is a non generic version of the type, which works with objects. |
The namespace is: |
using System.Collections; |
GoalKicker.com – .NET Framework Notes for Professionals |
19 |
And a code sample of non generic stack: |
Stack stack = new Stack(); |
stack.Push("Hello World"); // string |
stack.Push(5); // int |
stack.Push(1d); // double |
stack.Push(true); // bool |
stack.Push(new Product()); // Product object |
object value; |
value = stack.Pop(); // return Product (Product type) |
value = stack.Pop(); // return true (bool) |
value = stack.Pop(); // return 1d (double) |
value = stack.Pop(); // return 5 (int) |
value = stack.Pop(); // return Hello World (string) |
There is also a method called Peek() which returns the last element added but without removing it from the Stack. |
Stack<int> stack = new Stack<int>(); |
stack.Push(10); |
stack.Push(20); |
var lastValueAdded = stack.Peek(); // 20 |
It is possible to iterate on the elements on the stack and it will respect the order of the stack (LIFO). |
Stack<int> stack = new Stack<int>(); |
stack.Push(10); |
stack.Push(20); |
stack.Push(30); |
stack.Push(40); |
stack.Push(50); |
foreach (int element in stack) |
{ |
Console.WriteLine(element); |
} |
The output (without removing): |
50 |
40 |
30 |
20 |
10 |
Section 5.3: Creating an initialized List with Custom Types |
public class Model |
{ |
public string Name { get; set; } |
public bool? Selected { get; set; } |
} |
Here we have a Class with no constructor with two properties: Name and a nullable boolean property Selected. If we |
wanted to initialize a List<Model>, there are a few different ways to execute this. |
GoalKicker.com – .NET Framework Notes for Professionals |
20 |
var SelectedEmployees = new List<Model> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.