首页 > 解决方案 > 使用 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[] 的括号之间需要一些东西,但我想不通

标签: c#winforms

解决方案


如果你想要,有疑问Array.BinarySearch。为了使用它,你应该

  1. 有一个数组 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"); 
 }

推荐阅读