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

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.

主站蜘蛛池模板: 兴隆县| 海伦市| 茌平县| 彰武县| 龙井市| 辰溪县| 湖北省| 那坡县| 鄂州市| 滨州市| 莎车县| 库尔勒市| 噶尔县| 犍为县| 行唐县| 咸宁市| 辉县市| 曲麻莱县| 富源县| 抚顺市| 兴义市| 元阳县| 邵阳县| 土默特右旗| 扶余县| 华坪县| 白山市| 文化| 黄平县| 杭锦旗| 蓬溪县| 东丽区| 凤台县| 横峰县| 安龙县| 大关县| 河西区| 金山区| 大余县| 尼木县| 清徐县|