if函数有问题。 我有3个字符串数组(“orderID”,“id”和“name”)
我想如果“orderID”匹配“id”,“name”要添加到列表中,如果不匹配则字符串“Not found in database”将被添加。
当前代码:
string x = "Not found in database";
for (int i = 0; i < id.Length; i++)
{
foreach (string ids in orderID)
{
if (ids == id[i])
{
listBox1.Items.Add(name[i]);
listBox2.Items.Add(name[i]);
break;
}
else
{
listBox2.Items.Add(x);
}
}
}
结果如下:
问题:
答案 0 :(得分:0)
经过测试的代码
var orderIds = new[] {"3", "5"}.ToList();
var ids = new[] { "1", "2", "3", "4", "5" }.ToList();
var names = new[] { "1", "2", "3", "4", "5" }.ToList();
foreach (var orderId in orderIds)
{
if (ids.Contains(orderId))
{
listBox1.Items.Add(names[ids.IndexOf(orderId)]);
}
else
{
listBox1.Items.Add("Not in the list");
}
}
答案 1 :(得分:0)
第二个列表 - 当“orderID”与“id”匹配时,“name”被添加到 列表,但不是在期望的位置。我猜这是在增加位置 数据库。如何避免?
您可以使用OrderBy()
订购商品:
List<string> orderedList = list.OrderBy(i => i);
这将按字母顺序按内容排序。如果您想颠倒顺序,可以使用OrderByDescending()
。
第三个列表只是重复,添加了“else”。否则它不起作用 expect.It正在为所有内容添加“未在数据库中找到”。任何 建议如何解决它?
我不确定您的id
和orderID
变量是字符串还是数组(最好提一下)。但是对于数组,您可能需要检查所需的数组是否包含需要Id
,而不是逐个进行比较。
for (int i = 0; i < id.Length; i++)
{
if(orderID.Contains(id[i])
{
listBox1.Items.Add(name[i]);
listBox2.Items.Add(name[i]);
}
else
{
listBox2.Items.Add(x);
}
}
如果是字符串,你只想比较它们(不是逐个符号)。
请正确命名变量并显示其类型,因为它可以帮助那些试图回答您问题的人。