【问题标题】:In-built binary search not searching properly [duplicate]内置二进制搜索无法正确搜索[重复]
【发布时间】:2019-12-04 10:04:51
【问题描述】:

所以我尝试使用 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");
}

如果您需要我的其他任何东西,请在 cmets 中找到 hmu

*EDIT: 数组已排序,“cust”数组是对象而不是字符串

【问题讨论】:

  • 你认为Array.BinarySearch 是做什么的?显然cust[found] == tbCUSTOMERID.Text 会返回false,因为cust 是一个复杂对象,而不是string(我假设tbCUSTOMERID.Textstring)。
  • 是的,你是对的,它是一个字符串,你知道解决这个问题吗?
  • @ZevSpitz 这有点无关紧要 - OP 抱怨无条件显示 MessageBox.Show("Customer doesn't exist"); 无条件显示......这有点......预期的行为?
  • 为避免询问 cmets 下一个问题,请重新阅读 minimal reproducible example 发布代码指南。看起来您的实际问题已经在 SO 上得到解答(即“按属性查找对象”或“按属性使用二进制搜索”),其中一个链接的重复项应该会给您答案。

标签: c# binary-search


【解决方案1】:

所以看来cust数组的item类型是这样的:

public class CustItem
{
    public string GScID { get; set; }
    public string GSname { get; set; }
    public string GSlocation { get; set; }
    public string GSemail { get; set; }
}

我建议(假设 GScID 是唯一的)将这些值存储在 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");
}

【讨论】:

  • 或许澄清cust本身不是CustItem,而是CustItem[]
  • @Zev 我的错。完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
  • 2020-11-16
  • 2019-05-02
  • 1970-01-01
  • 2020-01-19
  • 1970-01-01
  • 2020-10-25
相关资源
最近更新 更多