Search sorted List for an element with default comparer and returns the zero-based index of the element in CSharp

Description

The following code shows how to search sorted List for an element with default comparer and returns the zero-based index of the element.

Example


using System;// w  ww  .ja v  a 2 s. c  om
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");
        }
        
        
        foreach(string myD in myData)
        {
            Console.WriteLine(myD);
        }

    }
}

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