Ignora collegamentiHome / Blog

Blog


How to use ArrayList in C#

This simple example shows how to use ArrayList in C#.

using System;
using System.Collections;

class ArrayListTest
{   
	public static void Main()   
	{   
		// Create a "List" of Person
		ArrayList personList = new ArrayList();
		
		// Add some "Person" in the ArrayList
		personList.Add(new Person("Barbara", "Denver", 34));
		personList.Add(new Person("Sofia", "Brucks", 32));
		personList.Add(new Person("Elena", "Silver", 31));
		personList.Add(new Person("Asia", "Solis", 38));
		personList.Add(new Person("Paris", "Jordan", 25));
		
		// Print the information of persons
		Console.WriteLine("List of Person (not sorted)");
		foreach(Person p in personList)
		{
			Console.WriteLine(p.ToString());
		}
		
		// Sort person according to their age
		personList.Sort();
		
		// Print the information of persons
		Console.WriteLine();
		Console.WriteLine("List of Person (sorted)");
		foreach(Person p in personList)
		{
			Console.WriteLine(p.ToString());
		}
	}
}


/// <summary>
/// A typical sample class for objects of type Person
/// This class implements the interface IComparable
/// </summary>
class Person : IComparable
{
	string name;
	string surname;
	byte age;
	
	public Person()
	{}
	
	public Person(string n, string s, byte a)
	{
	name = n;
	surname = s;
	age = a;
	}
	
	public override string ToString()
	{
		return name+ ", " + surname + ", (" + age + ")";
	}
	
	public int CompareTo(object obj)
	{
        if(obj is Person) {
            Person p = (Person) obj;
            return age.CompareTo(p.age);
        }
        throw new ArgumentException("object is not a Person");    
    }
}

This is the output of the program:

List of Person (not sorted)
Barbara, Denver, (34)
Sofia, Brucks, (32)
Elena, Silver, (31)
Asia, Solis, (38)
Paris, Jordan, (25)

List of Person (sorted)
Paris, Jordan, (25)
Elena, Silver, (31)
Sofia, Brucks, (32)
Barbara, Denver, (34)
Asia, Solis, (38)



Category: C#