c# - 使用 Array.BinarySearch 在文本框上返回字符串
问题描述
我目前正在尝试使用内置Array.BinarySearch
函数来搜索列表框中的项目。这是一个项目,所以我必须按照要求的方式去做。
就目前而言,我正在将信息输入到一个文本框中,右键单击它会弹出一个 ContextMenuStrip 然后我应该能够单击它,它将在列表视图中搜索匹配的数据并填充与该数据一起使用的其他文本框.
如果您查看下面的图片,这将有助于了解我正在做的事情。
这是我的代码Binary.Search
。
private void text_Opening(object sender, CancelEventArgs e)
{
Customer findCustomer = new Customer();
// Value to search for
string target = txtCustID.Text;
int pos = Array.BinarySearch(myCustomer, target);
if (string.Compare(myCustomer[], target, true) == 0)
{
MessageBox.Show("Customer found");
txtCustID.Text = findCustomer.gsCustID;
txtFullName.Text = findCustomer.gsFullname;
txtCity.Text = findCustomer.gsFullname;
txtEmail.Text = findCustomer.gsEmail;
}
else
MessageBox.Show("Customer not found");
}
我目前在 myCustomer[] 的括号之间需要一些东西,但我想不通
解决方案
如果你想要,有疑问Array.BinarySearch
。为了使用它,你应该
- 有一个数组
Customer[] myCustomer
Customer
必须实现IComparable<Customer>
接口myCustomer
必须按升序排序- 您必须将
Customer
实例放入Array.BinarySearch
(您不能只放入txtCustID.Text
)
在一般情况下,如果您有一个集合Customer
,例如
Customer[] myCustomer = ...
你可以试试Linq
using System.Linq;
...
private void text_Opening(object sender, CancelEventArgs e) {
// Here, in the FirstOrDefault, we can put any condition
Customer findCustomer = myCustomer
.FirstOrDefault(customer => customer.CustId == txtCustID.Text);
if (findCustomer != null) {
// Customer found, (s)he is findCustomer
MessageBox.Show("Customer found");
// ...
}
else
MessageBox.Show("Customer not found");
}
编辑:如果您坚持Array.BinarySearch
(并且满足所有要求,请注意myCustomer
应按升序排序CustId
)然后
private void text_Opening(object sender, CancelEventArgs e) {
// We prepare artificial Customer to be found
Customer customerToFind = new Customer() {
CustId == txtCustID.Text,
};
int index = Array.BinarySearch(myCustomer, customerToFind);
if (index >= 0) {
Customer findCustomer = myCustomer[index];
MessageBox.Show("Customer found");
// ...
}
else
MessageBox.Show("Customer not found");
}
推荐阅读
- javascript - Google line chart: How to compare values from different time periods?
- javascript - 如果在外面单击,如何使模态消失
- excel - 向下拖动时,Excel公式索引和匹配不更新
- autodesk-forge - 如何使用 globalID 隔离查看器?
- python - Python:将(0...无穷大)范围内的值标准化为(0...1)。当输入是唯一的时,数据框中所有行的输出都是相同的
- c++ - 从 base64string 转换为 json wuth jsoncons
- python - 节点请求与 python 会话
- reactjs - 在 React JSX 中克隆字典
- java - Serializable ThreadLocal 是如何实现的?
- android - 如何处理片段回栈