Ler*_*oms 5 c# arrays binary-search
我正在尝试使用已输入文本框中的文本搜索对象数组。
我已经将对象数组转换为字符串数组,但是我仍然没有找到正确的索引
我按照要求在 c# 中使用内置的二进制搜索选项。我无法改变这一点。
如果有人可以提供帮助,那就太好了 - 如果您需要我的任何东西,请不要害怕给我留言。
这是客户数组
Customer[] cust = new Customer[20];
Run Code Online (Sandbox Code Playgroud)
这里是customer类的排序方法
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]);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
和交换例程
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;
}
Run Code Online (Sandbox Code Playgroud)
这是客户类
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是搜索方法
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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果你看看你的代码的这一部分:
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);
Run Code Online (Sandbox Code Playgroud)
在执行BinarySearch. 这将打破现有的排序。
查看文档
使用指定的比较器在整个排序列表中搜索元素,并返回该元素的从零开始的索引。
整个数组应该已经在BinarySearch. 因此,在添加这些新对象后,您需要再次对数组进行排序Customer。或者您应该将这些新Customer对象添加到已排序字符串中的正确索引中,以便它可以保持正确的排序。
还有另一个错误,该customerSort函数使用GSname字段排序。但string[] str数组由GScID字段组成。您应该对相同的事物进行排序和搜索。
所以,你的代码有问题。如果您确保排序,那么它应该可以工作。