Search sorted List for an element with specified 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 specified comparer and returns the zero-based index of the element.
Example
using System;// w w w.j a v a 2 s .c om
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");
MyComparer dc = new MyComparer();
myData.Sort(dc);
String insert = "java2s.com";
int index = myData.BinarySearch(insert, dc);
if (index < 0)
{
myData.Insert(~index, insert);
}
foreach (string s in myData)
{
Console.WriteLine(s);
}
}
}
The code above generates the following result.