students.Add( "Jenny" );
For every item in your collection, you need a new line that Adds items.
To access the items in your List, you can use a foreach loop. Add this to your button code:
foreach (string child in students)
{
listBox1.Items.Add( child );
}
So we're looping round all the items in the List, and then adding them to the listbox.
You can also use an ordinary for loop:
for (int i = 0; i < students.Count; i++)
{
listBox1.Items.Add( students[i] );
}
Notice that the end condition is students.Count. Count is a property of Lists that tells you how many items is in it. Inside the for loop, we're using square brackets with the index number inside. This is just like the normal arrays you used earlier.
But if you want to loop round a collection, the above code is not the right choice. A better choice is a foreach loop.
A foreach loop ends when no more items in your collection or array are left to examine. Unlike a normal for loop, you don't have to tell C# when this is - it already knows what's in your collection, and is clever enough to bail out of the foreach loop by itself.
You can add a new item to your List at any time. Here's an example to try:

So we're adding a fourth student to the List, Azhar, and then displaying the item in the listbox.
Add the new code to your button. Run your programme and click your button. Your form will look something like this:

Sorting a List
Sorting a List alphabetically is quite straightforward. You just use the Sort Method. Like this:
students.Sort();
And here's some code to try out. The new lines should be added at the end of your current code:
students.Sort();
listBox1.Items.Add("=================");
foreach (string child in students)
{
listBox1.Items.Add(child);
}
Run your programme and try it out. Here's what your listbox will look like after the button is clicked:

As you can see, the items have been sorted alphabetically, in ascending order. You can have a descending sort, if you prefer. One way to do this is with the Reverse method:
students.Reverse( );
No extra coding is needed!
Removing items from a List
To remove an item from your list, you can either use the Remove or the RemoveRange methods. The Remove method deletes single items from the List. You use it like this:
students.Remove( "Peter" );
In between the round brackets of Remove, you simply type the item you want to remove.
If you want to remove more than one item, use RemoveRange. Like this:
students.RemoveRange( 0, 2 );
The first number between the round brackets of RemoveRange is where in your list you want to start. The second number is how many items you want to remove. Here's some code to try at the end of your button:
students.RemoveRange(0, 2);
listBox1.Items.Add("=================");
foreach (string child in students)
{
listBox1.Items.Add(child);
}
But that's enough of Lists. There's lots more that you can do with them, and they are worth researching further.
The final Collection we'll look at is called a Hashtable.



