如何确定数组中的对象数

时间:2021-11-25 21:40:26

Once again I cannot find a solution myself (I have tried using Array.IndexOf(db, accnum) with a pos > -1 return boolean, but have reverted to this loop after I couldn't make it work). So, I thought using db.Length would leave 'a' at the length of all the non-null elements in the array, however it seems to count the whole array, meaning that when the loop reaches a null element it causes an error. Is there a way to halt the loop count when it runs out of objects in the array?

我再一次无法找到解决方案(我尝试使用带有pos> -1返回布尔值的Array.IndexOf(db,accnum),但在我无法使其工作后又恢复到此循环)。所以,我认为使用db.Length会在数组中所有非null元素的长度上留下'a',但它似乎计算整个数组,这意味着当循环到达null元素时会导致错误。有没有办法在数组中的对象用尽时停止循环计数?

void withdrawal()
{
    int accnum;
    double withdrawal;

    //get and parse input details
    accnum = int.Parse(tbNameEnt.Text);
    withdrawal = double.Parse(tbBalaEnt.Text);

    //check if account exists within existing objects
    int a = db.Length;
    for (int i = 0; i < a; i++)
    {
        if (db[i].GetAccNo() == accnum)
        {
            pos = i;

            //deduct from balance
            db[pos].SetBalance(db[pos].GetBalance() - withdrawal);

            WithMess(); //success message
            hide_form();
            MakeWith2.Visible = false;
            show_menu();
            break;
        }

        else if ((db[i].GetAccNo() != accnum) && (i == db.Length - 1))
        {
            //account doesn't exist message
            MessageBox.Show("Account does not exist");
        }
    }
}

1 个解决方案

#1


1  

If there are null items that pad the array.. break out of the loop when you reach one:

如果有填充数组的空项...当你到达一个时,跳出循环:

for (int i = 0; i < a; i++) {
   if (db[i] == null)
        break;
   // the rest

Alternatively, use LINQ to filter the null items out:

或者,使用LINQ过滤掉空项:

foreach (var item in db.Where(x => x != null)) {
    // loop here
}

#1


1  

If there are null items that pad the array.. break out of the loop when you reach one:

如果有填充数组的空项...当你到达一个时,跳出循环:

for (int i = 0; i < a; i++) {
   if (db[i] == null)
        break;
   // the rest

Alternatively, use LINQ to filter the null items out:

或者,使用LINQ过滤掉空项:

foreach (var item in db.Where(x => x != null)) {
    // loop here
}