|
C# Examples: A List Class |
|
using System;
public class List
{
private int size;
private string[] items;
public List()
{
size = 0;
items = new string[5];
}
public void Add(string item)
{
if (size >= items.Length)
Array.Resize<string>(ref items, items.Length + 5);
items[size] = item;
size++;
}
public int IndexOf(string item)
{
int index = -1;
for (int i = 0; i < size; i++)
if (items[i].Equals(item))
index = i;
return index;
}
public void Remove(string item)
{
int index = IndexOf(item);
if (index >= 0)
{
for (int i = index; i < size; i++)
items[i] = items[i + 1];
size--;
}
}
public void RemoveAt(int index)
{
if( (index >= 0) && (index < size) )
{
for (int i = index; i < size; i++)
items[i] = items[i + 1];
size--;
}
}
public string this[int index]
{
get
{
return items[index];
}
}
public int Count
{
get
{
return size;
}
}
}
public class Exercise
{
static int Main()
{
string name = "";
List lstNames = new List();
name = "Gertrude Monay"; lstNames.Add(name);
Console.WriteLine("Current Count: {0}", lstNames.Count);
name = "Hélène Mukoko"; lstNames.Add(name);
Console.WriteLine("Current Count: {0}", lstNames.Count);
name = "Patricia Katts"; lstNames.Add(name);
name = "Raymon Kouma"; lstNames.Add(name);
Console.WriteLine("Current Count: {0}", lstNames.Count);
name = "Peter Mukoko"; lstNames.Add(name);
name = "Harij Khan"; lstNames.Add(name);
name = "Dominique Monayong"; lstNames.Add(name);
Console.WriteLine("Current Count: {0}", lstNames.Count);
name = "Ursula Andress"; lstNames.Add(name);
name = "Alexander Chance"; lstNames.Add(name);
name = "April Stevens"; lstNames.Add(name);
name = "Daniel Lanson"; lstNames.Add(name);
Console.WriteLine("Current Count: {0}", lstNames.Count);
Console.WriteLine("=--------------------------------=");
for (int i = 0; i < lstNames.Count; i++ )
Console.WriteLine("{0}: {1}", i + 1, lstNames[i]);
Console.WriteLine("Indef of Alexander Chance is {0}",
lstNames.IndexOf("Alexander Chance"));
Console.WriteLine("=--------------------------------=");
lstNames.Remove("Peter Mukoko");
Console.WriteLine("Current Count: {0}", lstNames.Count);
for (int i = 0; i < lstNames.Count; i++)
Console.WriteLine("{0}: {1}", i + 1, lstNames[i]);
Console.WriteLine("=--------------------------------=");
lstNames.RemoveAt(3);
Console.WriteLine("Current Count: {0}", lstNames.Count);
for (int i = 0; i < lstNames.Count; i++)
Console.WriteLine("{0}: {1}", i + 1, lstNames[i]);
Console.WriteLine("=--------------------------------=");
Console.WriteLine();
return 0;
}
}
|
|