在 C# 中将二进制搜索解析为数组列表
Parsing binary search as an arraylist in C#
有什么方法可以缩短这段代码吗?
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];
您似乎把事情复杂化了,您当然不应该将数字转换为字符串只是为了将其解析回数字。
int index = ListOfPeople.BinarySearch(searchBar.Text);
当找不到该项目时,这将 return 一个非负数。它不是 return int?
,而是 return 和 int
。
现在您可以使用它了:
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
}
有什么方法可以缩短这段代码吗?
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];
您似乎把事情复杂化了,您当然不应该将数字转换为字符串只是为了将其解析回数字。
int index = ListOfPeople.BinarySearch(searchBar.Text);
当找不到该项目时,这将 return 一个非负数。它不是 return int?
,而是 return 和 int
。
现在您可以使用它了:
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
}