C# List BinarySearch(T, IComparer)
Description
List
searches
the entire sorted List
Syntax
public int BinarySearch(
T item,
IComparer<T> comparer
)
Parameters
item
- The object to locate. The value can be null for reference types.comparer
- The IComparerimplementation to use when comparing elements. comparer
- -or-comparer
- null to use the default comparer Comparer.Default.
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;//ww w. j a v a2 s . com
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.