Skip to main content
 首页 » 编程设计

C# arraylist 搜索对象属性问题

2024年02月23日14lovecherry

我在这里似乎看不到我的错误。我知道这不是最好的方法,但我有义务使用 Arraylist。

无论如何,我知道我的数组列表包含正确的元素,我想知道我的 Item 类的属性 Number 是否与“searchNr”相同。

如果是,我想使用 ToString() 打印出该元素。如果我搜索“107”(Arraylist 中最后一个元素的 Number 属性,我确实找到了它。但找不到任何其他数字属性。除了 If 语句(如(等于)),我可以使用其他任何东西吗?

public void Search(object sender, EventArgs e) 
    { 
        string searchNrString = searchTextBox.Text; 
        int searchNr = Int32.Parse(searchNrString); 
 
 
        foreach (Item product in item)     
        {                                  
 
            if (product.Number == searchNr)  //if we find the number 
            { 
                resultTextBox.Text = ((Item)product).ToString();     
 
            } 
            else if ( product.Number != searchNr)    //if we don't find the number 
            { 
                string debug; 
                debug = string.Format("Could not find the number {0}  arraylist :{1}", product.Number, item.Count); //debug här! 
                resultTextBox.Text = debug; 
            } 
        } 
    }  

请您参考如下方法:

您需要添加一个 break 语句来在找到所需项目后退出循环:

if (product.Number == searchNr)  //if we find the number 
{ 
    resultTextBox.Text = ((Item)product).ToString();     
    break; 
} 

否则您可能会找到该项目,但您的循环会一直持续到结束,因此该数字不再与后续项目匹配,从而导致评估您的 else 语句。这就是为什么您似乎总是在列表中找到最后一个元素(即“107”条目)。