首页 > 解决方案 > 内置二分搜索未正确搜索

问题描述

所以我试图在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”数组是对象而不是字符串

标签: c#binary-search

解决方案


所以看起来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");
}

推荐阅读