Search code examples
c#winformsbinary-search

Parsing binary search as an arraylist in C#


Is there any possible way to make this code shorter?


            int? index = ListOfPeople.BinarySearch(searchBar.Text);
            int? temp = int.TryParse(index.ToString(), out int i) ? (int?)1 : null;
            MyPeopleGrid.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
            MyPeopleGrid.Rows[i].Selected = true;
            MyPeopleGrid.CurrentCell = MyPeopleGrid.Rows[i].Cells[0];

Solution

  • You seem to have seriously overcomplicated things, and you certainly should never convert a number to a string only to parse it back to a number.

    int index = ListOfPeople.BinarySearch(searchBar.Text);
    

    This will return a non-negative number when the item isn't found. It does not return int?, it returns int.

    So now you can use it:

    int index = ListOfPeople.BinarySearch(searchBar.Text);
    if (index >= 0)
    {
        MyPeopleGrid.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
        MyPeopleGrid.Rows[index].Selected = true;
        MyPeopleGrid.CurrentCell = MyPeopleGrid.Rows[index].Cells[0];
    }
    else
    {
        // do something when the item isn't found
    }