This program illustrates how to accept any number of names into an ArrayList. It asks the user to enter the last name then first name of the person. The input is controlled by a sentinel value where the user is asked to enter the word “END”. It can be in either lower or upper case. After typing end, the program will show a sorted list of the names entered.
This program makes use of a separate method to perform the sort function, all though it could have all been done under the Main method. It uses the string.ToUpper method for the sentinel value and makes use of the break statement in the loop so as to not add any variant of the word “END” in the list.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace pe7_5
{
class SortingArray
{
static void Main(string[] args)
{
ArrayList lnameFname = new ArrayList();
string sentinel = "";
int alCount;
Console.WriteLine("Enter the last and first " +
"name of a person. " +
"Type END to exit");
while (sentinel != "END")
{
Console.Write("Last Name & First Name: ");
sentinel = Console.ReadLine();
if (sentinel.ToUpper() == "END")
break;
lnameFname.Add(sentinel);
}
alCount = lnameFname.Count;
ArraySort(lnameFname, alCount);
Console.Write("The Program has terminated. Press [ENTER] to exit.");
Console.ReadLine();
}// end Main method
static void ArraySort(ArrayList lnameFname, int alCount)
{
lnameFname.Sort();
foreach (string lf in lnameFname)
Console.WriteLine(lf);
}
}
}