- 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.
推薦閱讀
- Mastering Zabbix(Second Edition)
- Python自動(dòng)化運(yùn)維快速入門(第2版)
- JIRA 7 Administration Cookbook(Second Edition)
- 薛定宇教授大講堂(卷Ⅳ):MATLAB最優(yōu)化計(jì)算
- Python程序設(shè)計(jì)案例教程
- SSM輕量級(jí)框架應(yīng)用實(shí)戰(zhàn)
- Learning Vaadin 7(Second Edition)
- ExtJS高級(jí)程序設(shè)計(jì)
- Linux C編程:一站式學(xué)習(xí)
- Flowable流程引擎實(shí)戰(zhàn)
- Visual FoxPro 6.0程序設(shè)計(jì)
- Visual Basic 程序設(shè)計(jì)實(shí)踐教程
- Get Your Hands Dirty on Clean Architecture
- Effective C++:改善程序與設(shè)計(jì)的55個(gè)具體做法(第三版)中文版(雙色)
- Learning Gerrit Code Review