c#各种类型循环的用法

本文关键字:用法 循环 类型 种类 | 更新日期: 2023-09-27 18:07:05

我对c#中的循环有点困惑,什么是各种循环的最佳用例,如for, foreach, while, do while, List.ForEach?

c#各种类型循环的用法

取决于用例。例如,如果您只想要数组中奇数个索引项,则在每次运行中使用+2的For循环。ForEach适用于标准循环。但在某些情况下,您不能使用其中的一个,例如,在foreach中,您不能从集合中删除项。在这种情况下,你需要e.g. for。当你有一个特定的条件时,你需要一个while循环

当您想设置计数器迭代时,可以使用for循环,例如

for(int i=0;i<3;i++)//will loop until it meets the condition i<3
{ //statement here}

如果要循环并显示变量的集合(如

),则使用foreach
string[] name = { "josh", "aj", "beard" };
    // ... Loop with the foreach keyword.
    foreach (string value in name)
    {
        Console.WriteLine(name);
    }
如果想在 语句之前先满足条件,则使用

while

while(condition)
{
//statement here
}
如果想在条件

之前先执行语句,则使用

do while。

do
{
//statement here
}
while(condition)