namespace The_List_Collection
{
/*
The List<T> is a generic collection.
Works like a dynamic array.
There are two main properties: Count & Capacity
Count: current number of items in the List
Capacity: current Max allowed
However when the List Count reaches the Capacity,
the capacity automatically doubles.
*
A List is just a dynamic array. Its size increases or
doubles each time the list is full.
Use the Add method to add new item to the list
Use Remove or RemoveAt to remove an item from the list
You may use the index to access any item in the list
*/
public partial class Form1 : Form
{
Random rand = new Random();
List<int> numbers = new List<int>(4);
public Form1()
{
InitializeComponent();
}
private void btnAddNumber_Click(object sender, EventArgs e)
{
//generate a random number
int n = rand.Next();
//add n to the list: numbers
numbers.Add(n);
//display the list in richtextbox1
DisplayList();
//display count and capacity in richtextbox2
DisplayCountCapacity();
}
//method to display the list numbers
private void DisplayList()
{
richTextBox1.Clear();
foreach (int n in numbers)
{
richTextBox1.AppendText(n + "\n");
}
}
//method to display Count and Capacity of list numbers
private void DisplayCountCapacity()
{
richTextBox2.Text = String.Format(
" Count: {0} \n Capacity: {1}", numbers.Count,
numbers.Capacity);
}
private void Form1_Load(object sender, EventArgs e)
{
DisplayCountCapacity();
}
private void btnTrim_Click(object sender, EventArgs e)
{
numbers.TrimExcess();
DisplayCountCapacity();
}
private void btnRemoveAt_Click(object sender, EventArgs e)
{
try
{
int index = int.Parse(txtIndex.Text);
numbers.RemoveAt(index);
DisplayList();
DisplayCountCapacity();
}
catch (FormatException fe)
{
MessageBox.Show(fe.Message);
}
catch (ArgumentOutOfRangeException ae)
{
MessageBox.Show(ae.Message + "\n"+
"Valid index: 0 to "+ (numbers.Count-1));
}
}
}
}

No comments:
Post a Comment