官术网_书友最值得收藏!

The foreach loop

This helps iterate an array element or collection. It does the same thing as the for loop, but this is available to iterate through a collection without the facility to add or remove items from collections.

Let's take a look at the following code snippet:

private static void ForEachStatementExample() 
{ 
WriteLine("foreach loop example"); 
char[] vowels = {'a', 'e', 'i', 'o', 'u'}; 
WriteLine("foreach on Array."); 
foreach (var vowel in vowels) 
    { 
        WriteLine($"{vowel}"); 
    } 
WriteLine(); 
var persons = new List<Person> 
    { 
     new Author {Name = "Gaurav Aroraa"}, 
     new Reviewer {Name = "ShivprasadKoirala"}, 
     new TeamMember {Name = "Vikas Tiwari"}, 
     new TeamMember {Name = "Denim Pinto"} 
    }; 
WriteLine("foreach on collection"); 
foreach (var person in persons) 
    { 
        WriteLine($"{person.Name}"); 
    } 
}

The preceding code is a working example of a foreach statement that prints a person's name. Name is a property in a collection of the Person object. The statement of the foreach block executes repeatedly until the expression person in persons evaluates to false.

主站蜘蛛池模板: 江达县| 余庆县| 麦盖提县| 新乐市| 巴林左旗| 新和县| 刚察县| 洛南县| 临潭县| 洞头县| 沅陵县| 奇台县| 鹤庆县| 汉源县| 钦州市| 垦利县| 兰溪市| 怀安县| 丹江口市| 仁布县| 苏尼特左旗| 平塘县| 江西省| 黔西县| 乌鲁木齐县| 远安县| 镇原县| 铁岭市| 张家港市| 广丰县| 绿春县| 鹿泉市| 天等县| 大姚县| 广灵县| 漳平市| 渭南市| 澄迈县| 巴东县| 山东| 柘城县|