IV.5.1 ArrayList
In C#, the ArrayList is a non-generic collection of objects whose size increases dynamically. It is the same as Array except that its size increases dynamically.
An ArrayList can be used to add unknown data where you don't know the types and the size of the data.
Create an ArrayList
The ArrayList class included in the System.Collections namespace. Create an object of the ArrayList using the new keyword.
Example: Create an ArrayList
using System.Collections;
ArrayList arlist = new ArrayList();
// or
var arlist = new ArrayList(); // recommended
Example:
Source Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections; //Add this line manually
namespace arraylist
{
public partial class Form1 : Form
{
ArrayList arr = new ArrayList();
public Form1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
arr.Add(txtItem.Text);
this.IstItem.DataSource = arr.ToArray();
txtItem.Clear();
txtItem.Focus();
}
private void btnSort_Click(object sender, EventArgs e)
{
arr.Sort();
this.IstItem.DataSource = arr.ToArray();
}
private void btnRemove_Click(object sender, EventArgs e)
{
arr.RemoveAt(this.IstItem.SelectedIndex);
this.IstItem.DataSource = arr.ToArray();
}
}
}
IV.5.2 Queue Collection
Queue is a special type of collection that stores the elements in FIFO style (First In First Out), exactly opposite of the Stack<T> collection. It contains the elements in the order they were added. C# includes generic Queue<T> and non-generic Queue collection. It is recommended to use the generic Queue<T> collection.
Example:
// C# code to create a Stack
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a Stack
Stack myStack = new Stack();
// Inserting the elements into the Stack
myStack.Push("1st Element");
myStack.Push("2nd Element");
myStack.Push("3rd Element");
myStack.Push("4th Element");
myStack.Push("5th Element");
myStack.Push("6th Element");
// Displaying the count of elements
// contained in the Stack
Console.Write("Total number of elements in the Stack are : ");
Console.WriteLine(myStack.Count);
// Displaying the top element of Stack
// without removing it from the Stack
Console.WriteLine("Element at the top is : " + myStack.Peek());
// Displaying the top element of Stack
// without removing it from the Stack
Console.WriteLine("Element at the top is : " + myStack.Peek());
// Displaying the count of elements
// contained in the Stack
Console.Write("Total number of elements in the Stack are : ");
Console.WriteLine(myStack.Count);
}
}
0 Comments