使用Array.BinarySearch返回文本框上的字符串

问题描述 投票:0回答:1

我目前正在尝试使用内置的Array.BinarySearch函数在列表框中搜索项目。这是针对项目的,因此我必须按要求的方式进行。

按现状,我正在一个文本框中输入信息,右键单击它会弹出一个ContextMenuStrip,然后我应该能够单击它,它将在列表视图中搜索匹配的数据并填充与该文本一起出现的其他文本框数据。

如果您在下面的图像中查找,这将有助于了解我在做什么。

enter image description here

这里是我的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 []的方括号之间需要一些内容,但我无法弄清楚]

c# winforms
1个回答
0
投票

不确定是否需要Array.BinarySearch。为了使用它,您应该

  1. 具有array Customer[] myCustomer
  2. [Customer必须实现IComparable<Customer>接口
  3. myCustomer必须以升序顺序排序
  4. 您必须将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"); }
© www.soinside.com 2019 - 2024. All rights reserved.