ArrayList.BinarySearch : ArrayList « System.Collections « C# / C Sharp by API






ArrayList.BinarySearch

  
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.new ArrayList()
2.new ArrayList(Collection c)
3.ArrayList.Add
4.ArrayList.AddRange
5.ArrayList.Capacity
6.ArrayList.Clear()
7.ArrayList.Clone
8.ArrayList.Contains
9.ArrayList.CopyTo
10.ArrayList.GetEnumerator()
11.ArrayList.GetRange
12.ArrayList.IndexOf
13.ArrayList.Insert
14.ArrayList.InsertRange()
15.ArrayList.IsFixedSize
16.ArrayList.IsReadOnly
17.ArrayList.LastIndexOf
18.ArrayList.Remove
19.ArrayList.RemoveAt
20.ArrayList.RemoveRange
21.ArrayList.Reverse()
22.ArrayList.SetRange
23.ArrayList.Sort()
24.ArrayList.Synchronized
25.ArrayList.ToArray
26.ArrayList.ToArray(typeof(T))
27.ArrayList.TrimToSize()