Binary search sub List for an element with specified comparer and returns the zero-based index in CSharp

Description

The following code shows how to binary search sub List for an element with specified comparer and returns the zero-based index.

Example


using System;/*w  w  w  . ja va  2 s. c  o  m*/
using System.Collections.Generic;

public class MyComparer: IComparer<string>
{
    public int Compare(string x, string y)
    {
        if (x == null || y == null){
           return 0;
        }
        return x.CompareTo(y);
    }
}

public class Example
{
    public static void Main()
    {
        List<string> myData = new List<string>();

        myData.Add("B");
        myData.Add("C");
        myData.Add("D");
        myData.Add("A");

        int m = 5;
        MyComparer dc = new MyComparer();

        myData.Sort(0, m, dc);
        int index = myData.BinarySearch(0, m, "W", dc);
        Console.WriteLine(index);
        
        if (index < 0)
        {
            myData.Insert(~index, "W");
            m++;
        }
        
        foreach(string s in myData){
        
        }
    }
}




















Home »
  C# Tutorial »
    Collections »




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