2011-11-10 84 views
1

我似乎无法看到我的错误在这里。我知道这不是最好的方法,但我有义务使用Arraylist。C#arraylist搜索对象属性问题

无论如何,我知道我的arraylist包含正确的元素,我想知道我的Item类的属性Number是否与'searchNr'相同。

如果是,我想用ToString()打印出该元素。如果我搜索“107”(Arraylist中最后一个元素的Number属性,我确实找到它了),但是找不到任何其他数字属性。

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; 
      } 
     } 
    } 
+0

ArrayList在哪里?另外,你使用的是什么版本的.NET? –

回答

4

您需要添加一个break声明退出循环一旦你找到所需的项目:

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

否则,你可能会找到该项目,但你的循环一直持续到年底,因此数不再匹配后续项目,导致您的else声明被评估。这就是为什么你总是看到最后的元素进入你的清单(即“107”条目)。

+0

问题解决了,谢谢! – user1040281

+1

@ user1040281太棒了!您应该考虑使用调试器逐步执行代码。如果你已经在你的循环中设置了一个断点并且通过了它,那么问题就会很明显:) –

+0

好的,再次感谢下次尝试,相当新的而不是使用调试器:) – user1040281