How to search an item in a C# List

Introduction

C# List<T> class provides methods and properties to create a list of objects (classes). You can add items to a list during the initialization or using List.Add() and List.AddRange() methods.

The list is a generic class. You must import the following namespace before using the List<T> class.

using System.Collections.Generic;

How to Search an Item in a List?

The BinarySearch method uses the binary search algorithm to find an item in the sorted List.

The following code snippet finds an item in a List.

// Create a list of strings
List<string> AuthorList = new List<string>();
AuthorList.Add("Mahesh Chand");
AuthorList.Add("Praveen Kumar");
AuthorList.Add("Raj Kumar");
AuthorList.Add("Nipun Tomar");
AuthorList.Add("Dinesh Beniwal");
AuthorList.Sort();
int itemPosition = AuthorList.BinarySearch("Raj Kumar");
Console.WriteLine("Item found at position: {0}", itemPosition + 1);

Next > C# List Tutorials


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.