C# List BinarySearch(Int32, Int32, T, IComparer)
Description
List
searches
a range of elements in the sorted List
Syntax
public int BinarySearch(
int index,//from w w w . jav a 2s .c om
int count,
T item,
IComparer<T> comparer
)
Parameters
index
- The zero-based starting index of the range to search.count
- The length of the range to search.item
- The object to locate. The value can be null for reference types.comparer
- The IComparerimplementation to use when comparing elements, or 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;//from www .ja 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");
myData.Add("A");
int m = 5;
MyComparer dc = new MyComparer();
myData.Sort(0, m, dc);
int index = myData.BinarySearch(0, m, "W", dc);
if (index < 0)
{
myData.Insert(~index, "W");
m++;
}
}
}