- 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.
推薦閱讀
- C語言程序設計案例教程
- 技術領導力:程序員如何才能帶團隊
- MATLAB應用與實驗教程
- Java Web基礎與實例教程
- Banana Pi Cookbook
- 名師講壇:Java微服務架構實戰(SpringBoot+SpringCloud+Docker+RabbitMQ)
- Mastering Drupal 8 Views
- 單片機應用與調試項目教程(C語言版)
- Mastering Data Mining with Python:Find patterns hidden in your data
- jQuery炫酷應用實例集錦
- Learning Apache Karaf
- Unity 3D/2D移動開發實戰教程
- R語言:邁向大數據之路(加強版)
- NGUI for Unity
- UX Design for Mobile