Ignora collegamentiHome / Blog

Blog


How to use ArrayList in C#

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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#