In this tutorial, i’ll show you How to search C# List elements.
The BinarySearch method of List<T> searches a sorted list and returns the zero-based index of the found item. The List<T> must be sorted before this method can be used.
The following code snippet returns an index of a string in a List.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | static void Main(string[] args) { List<string> colors = new List<string>(); colors.Add("Black"); colors.Add("White"); colors.Add("Blue"); colors.Add("Red"); colors.Add("Purple"); colors.Add("Yellow"); colors.Add("Green"); int bs = colors.BinarySearch("Black"); //Output: 0 Console.WriteLine(bs); bs = colors.BinarySearch("Red"); //Output: 3 Console.WriteLine(bs); bs = colors.BinarySearch("Orange"); //Output: -2 Console.WriteLine(bs); Console.ReadKey(); } |
Output:
0
3
-2