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

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.

主站蜘蛛池模板: 左权县| 孟州市| 阳泉市| 闽清县| 云霄县| 奉新县| 泾川县| 白城市| 衡东县| 涡阳县| 海林市| 灵山县| 竹溪县| 万安县| 朝阳县| 兖州市| 修文县| 漠河县| 万全县| 双桥区| 东乡族自治县| 太谷县| 沈阳市| 新营市| 阳信县| 什邡市| 山丹县| 舟曲县| 通江县| 昌平区| 双江| 奉新县| 安顺市| 博客| 西林县| 任丘市| 麻城市| 绵阳市| 宣武区| SHOW| 华宁县|