Search a range of elements in the sorted ArrayList with custom comparer and returns the zero-based index of the element in CSharp
Description
The following code shows how to search a range of elements in the sorted ArrayList with custom comparer and returns the zero-based index of the element.
Example
using System;/* ww w . j a va2 s. c o 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(0,3,"W", new SimpleStringComparer());
Console.WriteLine("Binary search, item found at index: {0}", index);
}
}
The code above generates the following result.