0
0
C Sharp (C#)programming~20 mins

Foreach loop over collections in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Foreach Loop Over Collections
📖 Scenario: You are helping a small bookstore organize its inventory. The store has a list of book titles, and you want to display each title to the customers.
🎯 Goal: Build a simple C# program that uses a foreach loop to go through a list of book titles and print each one.
📋 What You'll Learn
Create a list of book titles with exact values
Create a variable to count the number of books
Use a foreach loop to iterate over the list of book titles
Print each book title and the total count of books
💡 Why This Matters
🌍 Real World
Foreach loops are used in many programs to process lists of data, like showing items in a store or reading user inputs.
💼 Career
Understanding how to loop over collections is a basic skill for software developers, useful in data processing, UI lists, and more.
Progress0 / 4 steps
1
Create a list of book titles
Create a List<string> called books with these exact titles: "The Hobbit", "1984", "Pride and Prejudice", "To Kill a Mockingbird".
C Sharp (C#)
Need a hint?

Use List<string> and initialize it with the four book titles inside curly braces.

2
Create a counter variable
Create an integer variable called count and set it to 0 to keep track of the number of books.
C Sharp (C#)
Need a hint?

Declare int count = 0; inside the Main method.

3
Use a foreach loop to iterate over the list
Use a foreach loop with the variable book to go through each item in the books list. Inside the loop, print the current book and increase count by 1.
C Sharp (C#)
Need a hint?

Use foreach (string book in books) and inside the loop write Console.WriteLine(book); and count++;.

4
Print the total number of books
After the foreach loop, print the total number of books using Console.WriteLine with the message: Total books: followed by the count variable.
C Sharp (C#)
Need a hint?

Use Console.WriteLine($"Total books: {count}"); after the loop to show the total.