【发布时间】:2023-03-24 17:37:01
【问题描述】:
我正在尝试使用已在文本框中输入的文本搜索对象数组。
我已经将对象数组转换为字符串数组,但是我仍然没有找到正确的索引
我正在使用 C# 中的内置二进制搜索选项,因为这是已请求的。我无法改变这一点。
如果有人可以提供帮助,那就太好了 - 如果您需要我的任何东西,请不要害怕给我留言。
这是客户数组
Customer[] cust = new Customer[20];
这是客户类的排序方法
private void customerSort()
{
for (int y = 0; y < 20; y++)
{
for (int x = 0; x < customerPTR - 1; x++)
{
if (string.Compare(cust[x].GSname, cust[x + 1].GSname) > 0)
{
customerSwapRoutine(cust[x]);
}
}
}
}
和交换例程
private void customerSwapRoutine(Customer book, int x = 0)
{
string tempString = cust[x].GSname;
cust[x].GSname = cust[x + 1].GSname;
cust[x + 1].GSname = tempString;
string tempString2 = cust[x].GScID;
cust[x].GScID = cust[x + 1].GScID;
cust[x + 1].GScID = tempString2;
string tempString3 = cust[x].GSlocation;
cust[x].GSlocation = cust[x + 1].GSlocation;
cust[x + 1].GSlocation = tempString3;
string tempString4 = cust[x].GSemail;
cust[x].GSemail = cust[x + 1].GSemail;
cust[x + 1].GSemail = tempString4;
}
这是客户类
class Customer
{
private string name, location, email, cID;
public string GScID
{
get { return cID; }
set { cID = value; }
}
public string GSname
{
get { return name; }
set { name = value; }
}
public string GSlocation
{
get { return location; }
set { location = value; }
}
public string GSemail
{
get { return email; }
set { email = value; }
}
public string displayCustomer()
{
return GScID + " " + GSname + " " + GSlocation + " " + GSemail;
}
}
这里是搜索方法
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
string[] str = new string[cust.Length];
for(int y = 0; y < cust.Length; y++)
{
if(cust[y] == null)
{
Customer nc = new Customer();
cust[y] = nc;
cust[y].GScID = "";
cust[y].GSemail = "";
cust[y].GSlocation = "";
cust[y].GSname = "";
}
str[y] = cust[y].GScID;
}
string stringcID = tbCUSTOMERID.Text;
int found = Array.BinarySearch(str, stringcID);
if (found < 0)
{
MessageBox.Show("Customer doesn't exist");
}
else
{
MessageBox.Show("Customer found!");
tbCUSTOMERID.Text = cust[found].GScID;
tbCUSTOMERNAME.Text = cust[found].GSname;
tbCITY.Text = cust[found].GSlocation;
tbEMAIL.Text = cust[found].GSemail;
}
}
【问题讨论】:
-
您确认正在排序吗?因为您没有传递
x参数,所以我有理由相信此方法将始终查看数组的 0 和 1 元素,而不是在数组中移动。
标签: c# arrays binary-search