Search sorted ArrayList using the specified comparer and returns the zero-based index of the element in CSharp

Description

The following code shows how to search sorted ArrayList using the specified comparer and returns the zero-based index of the element.

Example


using System;//w w w.j av  a 2  s  .  co m
using System.Collections;

public class SimpleStringComparer : IComparer
{
    int IComparer.Compare(object x, object y)
    {
        string cmpstr = (string)x;
        return cmpstr.CompareTo((string)y);
    }
}

public class MyArrayList : ArrayList
{
    public static void Main()
    {
        MyArrayList coloredAnimals = new MyArrayList();

        coloredAnimals.Add("W");
        coloredAnimals.Add("P");
        coloredAnimals.Add("R");
        coloredAnimals.Add("G");
        coloredAnimals.Add("B");
        coloredAnimals.Add("A");
        coloredAnimals.Add("L");

        coloredAnimals.Sort();
        int index = coloredAnimals.BinarySearch("W", new SimpleStringComparer());
        Console.WriteLine("Binary search, item found at index:    {0}", index);
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Collections »




ArrayList
BitArray
Collection
Comparer
HashSet
Hashtable
LinkedList
List
ListDictionary
OrderedDictionary
Queue
SortedList
SortedSet
Stack
StringCollection
StringDictionary