ArrayList Sort

In this chapter you will learn:

  1. How to sort an ArrayList
  2. How to sort a list of customized objects

Sorting

The following code calls Sort method directly on the ArrayList instance.

using System;//from j ava2s.  c o  m
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class MainClass
{
    public static void Main()
    {

        // Create a new ArrayList and populate it. 
        ArrayList arraylist = new ArrayList(4);
        arraylist.Add("M");
        arraylist.Add("K");
        arraylist.Add("A");
        arraylist.Add("A");

        // Sort the ArrayList. 
        arraylist.Sort();

        // Display the contents of the sorted ArrayList. 
        Console.WriteLine("\nArraylist sorted by content");
        foreach (string s in arraylist)
        {
            Console.WriteLine(s);
        }

    }
}

The output:

Sort a list of customized objects

using System;//from ja va2 s  . c om
using System.Collections;

class Album : IComparable, ICloneable {
    private string _Title;
    private string _Artist;

    public Album(string artist, string title) {
        _Artist = artist;
        _Title = title;
    }

    public string Title {
        get {
            return _Title;
        }
        set {
            _Title = value;
        }
    }

    public string Artist {
        get {
            return _Artist;
        }
        set {
            _Artist = value;
        }
    }
    public override string ToString() {
        return _Artist + ",\t" + _Title;
    }
    public int CompareTo(object o) {
        Album other = o as Album;
        if (other == null)
            throw new ArgumentException();
        if (_Artist != other._Artist)
            return _Artist.CompareTo(other._Artist);
        else
            return _Title.CompareTo(other._Title);
    }
    public object Clone() {
        return new Album(_Artist, _Title);
    }
}

public class foo {
    public foo() {
        myString = "Test";
    }
    private string myString;
}

class MainClass {
    static void Main(string[] args) {
        ArrayList arr = new ArrayList();

        arr.Add(new Album("G", "A"));
        arr.Add(new Album("B", "G"));
        arr.Add(new Album("S", "A"));

        arr.Sort();
        arr.Insert(0, new foo());

        try {
            foreach (Album a in arr) {
                Console.WriteLine(a);
            }
        } catch (System.InvalidCastException e) {
        }

    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to convert ArrayList to array
  2. Cast to int and convert to list