Implement IComparer : IComparer « Class Interface « C# / C Sharp






Implement IComparer

  

using System;
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);
    }
}

class TitleComparer : IComparer {
    public int Compare(object l, object r) {
        Album left = l as Album;
        Album right = r as Album;
        if ((left == null) || (right == null))
            throw new ArgumentException();
        if (left.Title != right.Title)
            return left.Title.CompareTo(right.Title);
        else
            return left.Artist.CompareTo(right.Artist);
    }
}
class Class1 {
    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();
   
        try {
            foreach (Album a in arr) {
                Console.WriteLine(a);
            }
        } catch (System.InvalidCastException e) {
        }

        arr.Sort(new TitleComparer());
        foreach (Album a in arr) {
            Console.WriteLine(a);
        }

        Album l = new Album("L", "G");
        arr.Sort();
        int index = arr.BinarySearch(l);
        Console.WriteLine(index.ToString());
        arr.Sort(new TitleComparer());
        index = arr.BinarySearch(l, new TitleComparer());
        Console.WriteLine(index.ToString());
    }
}

   
  








Related examples in the same category

1.Gets the hash code for an object using a comparer. Correctly handles null.