C# List BinarySearch(T)

Description

List BinarySearch(T) searches the entire sorted List for an element using the default comparer and returns the zero-based index of the element.

Syntax

List.BinarySearch(T) has the following syntax.


public int BinarySearch(
  T item
)

Parameters

  • item - The object to locate. The value can be null for reference types.

Returns

Returns The zero-based index of item in the sorted List, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count.

Example


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

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

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

        foreach(string myD in myData)
        {
            Console.WriteLine(myD);
        }
        myData.Sort();

        foreach(string myD in myData)
        {
            Console.WriteLine(myD);
        }

        int index = myData.BinarySearch("newValue");
        if (index < 0)
        {
            myData.Insert(~index, "newValue");
        }

    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Collections.Generic »




HashSet
LinkedList
LinkedListNode
List
Queue
SortedSet
Stack