C# arraylist 搜索对象属性问题

标签 c# .net

我在这里似乎看不到我的错误。我知道这不是最好的方法,但我有义务使用 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”条目)。

关于C# arraylist 搜索对象属性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8084257/

相关文章:

.NET - 启用 UAC (Windows7/Vista) 时,应用程序如何能够 self 更新?

c# - Microsoft SqlServer 管理 : method not found creating a ServerConnection

c# - 更改系统时间不接受时区

c# - 在 C# 中使用典型的 get set 属性...带参数

c# - 我可以在创建对象之前计算属性吗?在构造函数中?

c# - 有没有办法等待所有任务直到特定结果为真,然后取消其余的?

.net - .NET 4 中的任务调度程序设计(任务并行库)

c# - 更改 EntityFramework 中的实体

c# - 为我覆盖 Mahapps Metro 风格标题 Tabitem

.net - 为什么 Task.WhenAll 上的等待不抛出 AggregateException?