c# - 内置二分搜索未正确搜索
问题描述
所以我试图在c#中使用内置的“Array.BinarySearch”函数搜索和对象数组但是,每当我搜索在文本框中输入的文本时,我都会收到我实现的“客户不存在”消息.
如果有人可以帮助我,那就太好了
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
int found = Array.BinarySearch(cust, tbCUSTOMERID.Text);
if (found == 0)
{
MessageBox.Show("Customer found!");
tbCUSTOMERID.Text = cust[found].GScID;
tbCUSTOMERNAME.Text = cust[found].GSname;
tbCITY.Text = cust[found].GSlocation;
tbEMAIL.Text = cust[found].GSemail;
}
MessageBox.Show("Customer doesn't exist");
}
如果您需要我的其他任何东西,请在评论中留言
*编辑:数组已排序,“cust”数组是对象而不是字符串
解决方案
所以看起来cust
数组的项目类型是这样的:
public class CustItem
{
public string GScID { get; set; }
public string GSname { get; set; }
public string GSlocation { get; set; }
public string GSemail { get; set; }
}
我建议(假设 GScID 是唯一的)将这些值存储在 a 中Dictionary<TKey, TValue>
,而不是数组中:
private IDictionary<string, CustItem> cust = new Dictionary<string, CustItem>();
cust.Add(item.GScID, item); // if you insert an existing key here, you will get a DuplicateKeyException
然后你可以按键引用它们:
if (cust.TryGetValue(tbCUSTOMERID.Text, out CustItem item))
{
MessageBox.Show("Customer found!");
tbCUSTOMERID.Text = item.GScID;
tbCUSTOMERNAME.Text = item.GSname;
tbCITY.Text = item.GSlocation;
tbEMAIL.Text = item.GSemail;
}
else
{
MessageBox.Show("Customer doesn't exist");
}
推荐阅读
- node.js - SQL Server 日志:错误 18456,严重性:14,状态:8 和 Visual Studio 终端:未定义
- r - 在 rmarkdown 中预览表格
- c# - IHostedService 多个实现的最佳实践
- typescript - 自定义类的类型转换
- javascript - addEventListener 不适用于切换按钮
- ruby-on-rails - Graphql-Client ruby OpenSSL::SSL::SSLError
- python - 使用 Regex Python 删除数据框中字符串中的前 2 个单词和后 2 个单词
- .net - WCF官方教程中的[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]是什么意思?
- javascript - 计算返回的子项数并使用赛普拉斯将子项属性推送到数组中
- r - R ggplot2 geom_area() 单行下方的颜色会产生奇怪的连接