We will begin our example using a string list array that will be called group which will do as we expect, hold strings. We will use this to store the names of people who are on a group project together. Sometimes people may need to be added or removed, 'tis the way it goes. We will fill the list with values to begin, and immediately sort the list to improve performance:
Now we will write code to search for Jojo. The code to produce this will use group.BinarySearch to find Jojo, and if she is not in the group, then she will be added at the correct location, being in alphabetical order. What this feature does exactly is it looks for the item you list, then we have to test what the return value of it is. If it returns -1, then the item is not within our list. If it returns any number greater than or equal to 0, then we know the item exists in our list already.
The code to produce this output is shown below:
So, if the index is not found in the list for Jojo, the program will insert her into the array at the location of ~nameOne, which will do the ground work for us and find the correct location. The output is shown below:
As you can see, Jojo has been added at the correct location for her name in alphabetical order.
So using the BinarySearch feature to look for an item within an index is very quick and simple in C# because of the built in functionality of Visual Studio.