C# While/for循环,直到出现特定条件

C# While/for循环,直到出现特定条件,c#,C#,我使用的是特定代码: while (!productsPage.FiltersComponent.TableComponent.CheckIfFilterResultsValid("Product Name", TableComparares.Exact, stockSimpleName)) { for (int i = 0; i < 3; i++) { productsPage.FiltersCo

我使用的是特定代码:

    while (!productsPage.FiltersComponent.TableComponent.CheckIfFilterResultsValid("Product Name", TableComparares.Exact, stockSimpleName))
    {
        for (int i = 0; i < 3; i++)
        {
            productsPage.FiltersComponent.DeleteSpecificFilterChip(stockSimpleName);
            productsPage.FiltersComponent.UseStringFilter(FiltersOptions.ProductName, stockSimpleName);

            if (i == 3) Assert.Fail("Product was not possible of being found after importing, tried three times");
        }
    }
while(!productsPage.FiltersComponent.TableComponent.CheckIfFilterResultsValid(“产品名称”,TableCompares.Exact,stockSimpleName))
{
对于(int i=0;i<3;i++)
{
productsPage.FiltersComponent.DeleteSpecificFilterChip(stockSimpleName);
productsPage.FiltersComponent.UseStringFilter(FiltersOptions.ProductName,stockSimpleName);
如果(i==3)Assert.Fail(“导入后不可能找到产品,尝试了三次”);
}
}
我想做什么:

我正在加载一个新文件,然后通过表过滤机制对其进行过滤,直到表中出现行(文件)。由于队列有时很短/有时很快,因此需要多长时间取决于服务器(最可能是3/4秒,但有时甚至需要30秒或更长时间)

加载文件后我的步骤是什么:

  • 按筛选器mechanizm搜索该文件(产品)名称
  • 检查结果是否出现在表结果中(while循环)
  • 删除筛选器(重新执行操作)
  • 重试此操作最多三次
  • Assert.Fail,表示文件未正确加载

现在,当第一次找不到产品,代码进入while/for循环时,它将进入不定循环,直到找到不好的产品。

你已经接近了,但还没有完全达到。基本上,您希望尝试某件事情3次,然后失败(
for
loop对此非常有效)。但是,只要
CheckIfFilterResultsValid
返回
true
您就想停止以后的任何尝试并停止循环。关键字
break
正是为此而设计的。它从它的外壳(
for
while
开关
)中脱离出来。所以它看起来像这样:

for (int i = 0; i <= 3; i++)
{
  if (i == 3) //check if we're tried 3 times already
    Assert.Fail("Product was not possible of being found after importing, tried three times"); //I assume this will throw an exception, if this does not break the flow you'll also have to add a break here!

  //check if it passes
  if (productsPage.FiltersComponent.TableComponent.CheckIfFilterResultsValid("Product Name", TableComparares.Exact, stockSimpleName))
    break; //this breaks out of the for loop

  //not made 3 attempts yet and not passed our check so do our attempt to fix
  productsPage.FiltersComponent.DeleteSpecificFilterChip(stockSimpleName);
  productsPage.FiltersComponent.UseStringFilter(FiltersOptions.ProductName, stockSimpleName);
}

用于(int i=0;i是一个定义良好、范围明确的问题,实际代码已经在其中,包括您想要什么、您尝试了什么以及如何提问的好例子。您的
Assert.Fail
将永远不会被调用。IF条件应该是
i==2
。riilight ok…但无论如何,我在for循环中的某个地方犯了错误。这将是perfect如果每次我删除并使用筛选器时都会检查while条件。现在检查三次,然后再检查条件。我试图达到的目的是:最多检查三次while条件,在每一次检查之后,我希望检查while条件。第三次检查失败后,我希望收到assert.Fail错误。for循环位于while循环内。因此,while条件仅在新for循环启动之前检查,而不是在启动期间检查。只有在for循环启动时才重新检查该条件done@Kermi请注意,
while
已消失,其状态在循环中移动,这正是我想要的,谢谢:)