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

  • Learn C# in 7 days
  • Gaurav Aroraa
  • 162字
  • 2021-07-08 09:51:29

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.

主站蜘蛛池模板: 华容县| 延安市| 伊通| 沙湾县| 朔州市| 美姑县| 理塘县| 西丰县| 调兵山市| 杨浦区| 姚安县| 巫山县| 宣恩县| 定远县| 会昌县| 哈密市| 道孚县| 伊金霍洛旗| 桃江县| 恩平市| 开远市| 孝感市| 沧源| 漳平市| 冷水江市| 河东区| 彭泽县| 沙洋县| 抚松县| 金阳县| 高碑店市| 韩城市| 曲阳县| 波密县| 伊春市| 耒阳市| 迁安市| 五指山市| 泰州市| 鹿邑县| 毕节市|