List BinarySearch() Method in C#
Last Updated :
11 Jul, 2025
List<T>.BinarySearch(T) Method uses a binary search algorithm to locate a specific element in the sorted List<T> or a portion of it. There are 3 methods in the overload list of this method as follows:
- BinarySearch(T)
- BinarySearch(T, IComparer<T>)
- BinarySearch(Int32, Int32, T, IComparer<T>)
BinarySearch(T) Method
This method searches for an element in the entire sorted List<T> using the default comparer and returns the zero-based index of the searched element.
Syntax:
public int BinarySearch (T item);
Here, item is the object which is to be locate and the value of item can be null or reference type.
Return Type: If the item is found, then this method returns the zero-based index of the element to be searched for and if not found, then a negative number that is the bitwise complement of the index of the next element will be return and the complement is larger than that item. If there is no larger element, the bitwise complement of Count will be return.
Exception: This method will give InvalidOperationException if the default comparer Default cannot find an implementation of the IComparable<T> generic interface or the IComparable interface for type T.
Below programs illustrate the use of above-discussed method:
Example 1:
C#
// C# program to illustrate the
// List<T>.BinarySearch(T) Method
using System;
using System.Collections.Generic;
class GFG {
// Main Method
public static void Main()
{
// List creation
List<string> Geek = new List<string>();
// List elements
Geek.Add("ABCD");
Geek.Add("QRST");
Geek.Add("XYZ");
Geek.Add("IJKL");
Console.WriteLine("The Original List is:");
foreach(string g in Geek)
{
// prints original List
Console.WriteLine(g);
}
Console.WriteLine("\nThe List in Sorted form");
// sort the List
Geek.Sort();
Console.WriteLine();
foreach(string g in Geek)
{
// prints the sorted List
Console.WriteLine(g);
}
Console.WriteLine("\nInsert EFGH :");
// insert "EFGH" in the List
//"EFGH" insert into its original
// position when the List is sorted
int index = Geek.BinarySearch("EFGH");
if (index < 0)
{
Geek.Insert(~index, "EFGH");
}
Console.WriteLine();
foreach(string g in Geek)
{
// prints the sorted list
// after inserting "EFGH"
Console.WriteLine(g);
}
}
}
OutputThe Original List is:
ABCD
QRST
XYZ
IJKL
The List in Sorted form
ABCD
IJKL
QRST
XYZ
Insert EFGH :
ABCD
EFGH
IJKL
QRST
XYZ
Example 2: In this example, the List is created with some integer values and to insert a new integer using BinarySearch(T) method in the List by using a user define function.
C#
// C# program to illustrate the
// List<T>.BinarySearch(T) Method
using System;
using System.Collections.Generic;
class GFG {
// method for inserting "3"
public void binarySearch(List<int> Geek)
{
// insert "3" in the List
Console.WriteLine("\nInsert 3 :");
// "3" insert into its original
// position when the List is
// sorted
int index = Geek.BinarySearch(3);
if (index < 0)
{
Geek.Insert(~index, 3);
}
foreach(int g in Geek)
{
// prints the sorted list
// after inserting "3"
Console.WriteLine(g);
}
}
}
// Driver Class
public class search {
public static void Main()
{
// List creation
GFG gg = new GFG();
List<int> Geek = new List<int>() {
5, 6, 1, 9};
Console.WriteLine("Original List");
foreach(int g in Geek)
{
Console.WriteLine(g);
// prints original List
}
Console.WriteLine("\nList in Sorted form");
Geek.Sort();
foreach(int g in Geek)
{
Console.WriteLine(g);
// prints the sorted List
}
// calling the method "binarySearch"
gg.binarySearch(Geek);
}
}
OutputOriginal List
5
6
1
9
List in Sorted form
1
5
6
9
Insert 3 :
1
3
5
6
9
BinarySearch(T) Method
This method searches for an element in the entire sorted List using the specified comparer and returns the zero-based index of the searched element.
Syntax:
public int BinarySearch (T item, System.Collections.Generic.IComparer<T> comparer);
Parameters:
- item : It is the item to locate and the value of the item can be null for reference types.
- comparer : It is the IComparer<T> implementation to use when comparing elements.
Return Value: If the item founds, then this method returns the zero-based index of the element to be searched for and if not found, then 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.
Exception: This method will give InvalidOperationException if the comparer is null, and the default comparer Default cannot find an implementation of the IComparable<T> generic interface or the IComparable interface for type T.
Below programs illustrate the use of the above-discussed method:
Example 1:
C#
// C# program to demonstrate the
// List<T>.BinarySearch(T,
// IComparer<T>) Method
using System;
using System.Collections.Generic;
class GFG : IComparer<string> {
public int Compare(string x, string y)
{
if (x == null || y == null)
{
return 0;
}
return x.CompareTo(y);
//"CompareTo()" method
}
}
// Driver Class
class geek {
// Main Method
public static void Main()
{
// list creation
List<string> list1 = new List<string>();
// list elements
list1.Add("B");
list1.Add("C");
list1.Add("E");
list1.Add("A");
// prints Original list
Console.WriteLine("Original string");
foreach(string g in list1)
{
Console.WriteLine(g);
}
GFG gg = new GFG();
// sort the list
list1.Sort(gg);
// prints the sorted form of original list
Console.WriteLine("\nList in sorted form");
foreach(string g in list1)
{
Console.WriteLine(g);
}
//"D" is going to insert
//"gg" is the IComparer
int index = list1.BinarySearch("D", gg);
if (index < 0)
{
list1.Insert(~index, "D");
}
// prints the final List
Console.WriteLine("\nAfter inserting \"D\" in the List");
foreach(string g in list1)
{
Console.WriteLine(g);
}
}
}
Output:
Original string
B
C
E
A
List in sorted form
A
B
C
E
After inserting "D" in the List
A
B
C
D
E
Example 2: In this example, the List is created with some integer values and to insert a new integer using BinarySearch(T, Comparer <T>) method in the List by using a user defined function.
C#
// C# program to demonstrate the
// List<T>.BinarySearch(T,
// IComparer<T>) Method
using System;
using System.Collections.Generic;
class GFG : IComparer<int> {
public int Compare(int x, int y)
{
if (x == 0 || y == 0)
{
return 0;
}
return x.CompareTo(y);
}
}
// Driver Class
class geek {
// Main Method
public static void Main()
{
// list creation
List<int> list1 = new List<int>() {
5, 6, 1, 9};
// prints Original list
Console.WriteLine("Original string");
foreach(int g in list1)
{
Console.WriteLine(g);
}
// creating object of class GFG
GFG gg = new GFG();
// sort the list
list1.Sort(gg);
// prints the sorted form
// of original list
Console.WriteLine("\nList in sorted form");
foreach(int g in list1)
{
Console.WriteLine(g);
}
bSearch b = new bSearch();
b.binarySearch(list1);
}
}
class bSearch {
public void binarySearch(List<int> list1)
{
// creating object of class GFG
GFG gg = new GFG();
// "3" is going to insert
// "gg" is the IComparer
int index = list1.BinarySearch(3, gg);
if (index < 0)
{
list1.Insert(~index, 3);
}
// prints the final List
Console.WriteLine("\nAfter inserting \"3\" in the List");
foreach(int g in list1)
{
Console.WriteLine(g);
}
}
}
OutputOriginal string
5
6
1
9
List in sorted form
1
5
6
9
After inserting "3" in the List
1
3
5
6
9
BinarySearch(Int32, Int32, T, IComparer<T>)
This method is used to search a range of elements in the sorted List<T> for an element using the specified comparer and returns the zero-based index of the element.
Syntax:
public int BinarySearch (int index, int count, T item, System.Collections.Generic.IComparer<T> comparer);
Parameters:
index: It is the zero-based starting index of the range to search.
count: It is the length of the range to search.
item: It is the object to locate. The value can be null for the reference type.
comparer: It is the IComparer implementation to use when comparing elements, or null to use the default comparer Default.
Return Value: It returns the zero-based index of item in the sorted List<T>, if the 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.
Exceptions:
- ArgumentOutOfRangeException: If the index is less than 0 or count is less than 0.
- ArgumentException: If the index and count do not represent a valid range.
- InvalidOperationException: If the comparer is null.
Example:
C#
// C# program to demonstrate the
// List<T>.BinarySearch(Int32,
// Int32, T, Comparer <T>) method
using System;
using System.Collections.Generic;
class GFG : IComparer<int>
{
public int Compare(int x, int y)
{
if (x == 0 || y == 0)
{
return 0;
}
return x.CompareTo(y);
}
}
class search {
// "binarySearch" function
public void binarySearch(List<int> list1,
int i)
{
Console.WriteLine("\nBinarySearch a "+
"range and Insert 3");
// "gg" is the object of class GFG
GFG gg = new GFG();
// binary search
int index = list1.BinarySearch(0, i,
3, gg);
if (index < 0)
{
// insert "3"
list1.Insert(~index, 3);
i++;
}
Display(list1);
}
// "Display" function
public void Display(List<int> list)
{
foreach( int g in list )
{
Console.WriteLine(g);
}
}
}
// Driver Class
class geek
{
// Main Method
public static void Main()
{
List<int> list1 = new List<int>()
{
// list elements
15,4,2,9,5,7,6,8,10
};
int i = 7;
Console.WriteLine("Original List");
// "d" is the object of
// the class "search"
search d = new search();
// prints Original list
d.Display(list1);
// "gg" is the object
// of class GFG
GFG gg = new GFG();
Console.WriteLine("\nSort a range with "+
"the alternate comparer");
// sort is happens between
// index 1 to 7
list1.Sort(1, i, gg);
// prints sorted list
d.Display(list1);
// call "binarySearch" function
d.binarySearch(list1,i);
}
}
OutputOriginal List
15
4
2
9
5
7
6
8
10
Sort a range with the alternate comparer
15
2
4
5
6
7
8
9
10
BinarySearch a range and Insert 3
15
2
3
4
5
6
7
8
9
10
Note:
- If the List<T> contains more than one element with the same value, the method returns only one of the occurrences, and it might return any one of the occurrences, not necessarily the first one.
- The List<T> must already be sorted according to the comparer implementation; otherwise, the result is incorrect.
- This method is an O(log n) operation, where n is the number of elements in the range.
Reference:
Similar Reads
Introduction
C# TutorialC# (pronounced "C-sharp") is a modern, versatile, object-oriented programming language developed by Microsoft in 2000 that runs on the .NET Framework. Whether you're creating Windows applications, diving into Unity game development, or working on enterprise solutions, C# is one of the top choices fo
4 min read
Introduction to .NET FrameworkThe .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The .NET framework is primarily used on Windows, while .NET Core (which evolved into
6 min read
C# .NET Framework (Basic Architecture and Component Stack)C# (C-Sharp) is a modern, object-oriented programming language developed by Microsoft in 2000. It is a part of the .NET ecosystem and is widely used for building desktop, web, mobile, cloud, and enterprise applications. This is originally tied to the .NET Framework, C# has evolved to be the primary
6 min read
C# Hello WorldThe Hello World Program is the most basic program when we dive into a new programming language. This simply prints "Hello World!" on the console. In C#, a basic program consists of the following:A Namespace DeclarationClass Declaration & DefinitionClass Members(like variables, methods, etc.)Main
4 min read
Common Language Runtime (CLR) in C#The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others.When a C# program is compiled, th
4 min read
Fundamentals
C# IdentifiersIn programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name, or label. Example: public class GFG { static public void Main () { int
2 min read
C# Data TypesData types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C# each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given pr
7 min read
C# VariablesIn C#, variables are containers used to store data values during program execution. So basically, a Variable is a placeholder of the information which can be changed at runtime. And variables allows to Retrieve and Manipulate the stored information. In Brief Defination: When a user enters a new valu
4 min read
C# LiteralsIn C#, a literal is a fixed value used in a program. These values are directly written into the code and can be used by variables. A literal can be an integer, floating-point number, string, character, boolean, or even null. Example:// Here 100 is a constant/literal.int x = 100; Types of Literals in
5 min read
C# OperatorsIn C#, Operators are special types of symbols which perform operations on variables or values. It is a fundamental part of language which plays an important role in performing different mathematical operations. It takes one or more operands and performs operations to produce a result.Types of Operat
7 min read
C# KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to be used as variable names or objects. Doing this will result in a compile-time error.Example:C#// C# Program to illustrate the
5 min read
Control Statements
C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. These
5 min read
C# Switch StatementIn C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type.
4 min read
C# LoopsLooping in a programming language is a way to execute a statement or a set of statements multiple times, depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops.Types of Loops in C#Loops are mainly divided
4 min read
C# Jump Statements (Break, Continue, Goto, Return and Throw)In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. In, this article, we will learn to different jump statements available to work in C#.Types of Jump StatementsThere are mainly five keywords in th
4 min read
OOP Concepts
Methods
Arrays
C# ArraysAn array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
8 min read
C# Jagged ArraysA jagged array is an array of arrays, where each element in the main array can have a different length. In simpler terms, a jagged array is an array whose elements are themselves arrays. These inner arrays can have different lengths. Can also be mixed with multidimensional arrays. The number of rows
4 min read
C# Array ClassArray class in C# is part of the System namespace and provides methods for creating, searching, and sorting arrays. The Array class is not part of the System.Collections namespace, but it is still considered as a collection because it is based on the IList interface. The Array class is the base clas
7 min read
How to Sort an Array in C# | Array.Sort() Method Set - 1Array.Sort Method in C# is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method as follows:Sort<T>(T[]) MethodSort<T>(T[], IComparer<T>) MethodSort<T>(T[], Int32, Int32) MethodSort<T>(T[], Comparison<T>) Method
8 min read
How to find the rank of an array in C#Array.Rank Property is used to get the rank of the Array. Rank is the number of dimensions of an array. For example, 1-D array returns 1, a 2-D array returns 2, and so on. Syntax: public int Rank { get; } Property Value: It returns the rank (number of dimensions) of the Array of type System.Int32. B
2 min read
ArrayList
String
Tuple
Indexers