Community for developers to learn, share their programming knowledge. Register!
C# Loops

Looping Through Collections in C#


You can get training on our this article to enhance your understanding of looping through collections in C#. Looping is a fundamental concept in programming, enabling developers to iterate over collections such as arrays, lists, and more. In C#, a variety of loop constructs are available, each offering unique features that can be leveraged based on the specific requirements of your application. This article will provide a comprehensive overview of how to effectively utilize C# loops to iterate through collections, complete with examples and best practices.

Using Loops to Iterate Over Collections

In C#, collections are data structures that hold multiple items, allowing for efficient data management and retrieval. The most common types of collections include arrays, lists, dictionaries, and sets. When it comes to iterating over these collections, C# provides several loop types, including:

  • for loop: A traditional loop where the number of iterations is known beforehand.
  • foreach loop: A specialized loop designed to iterate through collections without the need for an explicit index.
  • while loop: A loop that continues executing as long as a specified condition is true.
  • do-while loop: Similar to the while loop, but guarantees that the code block runs at least once.

Each of these loops has its use cases and advantages, making them suitable for different scenarios when working with collections.

The For Loop

The for loop is particularly useful when you know the exact number of iterations required. It provides greater control over the iteration process, including the ability to modify the index during each iteration.

Example of a for loop iterating through an array:

int[] numbers = { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}

In this example, the loop iterates over the numbers array, printing each element to the console.

The Foreach Loop

The foreach loop simplifies the process of iterating through collections by automatically handling the underlying index. This loop is ideal for cases where you do not need to modify the collection during the iteration.

Example of a foreach loop iterating through a list:

List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Here, the foreach loop iterates over the fruits list, printing each fruit name without the need for an explicit index.

The While Loop

The while loop is perfect for situations where the number of iterations is not known in advance, and the loop continues until a certain condition is met.

Example of a while loop:

int count = 0;
while (count < 5)
{
    Console.WriteLine("Count is: " + count);
    count++;
}

In this case, the loop will execute as long as count is less than 5, incrementing count with each iteration.

The Do-While Loop

Similar to the while loop, the do-while loop guarantees that the code block will execute at least once, regardless of the condition.

Example of a do-while loop:

int number;
do
{
    Console.WriteLine("Enter a positive number: ");
    number = Convert.ToInt32(Console.ReadLine());
} while (number <= 0);

In this example, the user is prompted to enter a positive number, with the loop continuing until a valid number is provided.

Examples of Looping Through Arrays and Lists

To illustrate the power of looping through collections in C#, consider the following scenarios:

Looping Through an Array

int[] primeNumbers = { 2, 3, 5, 7, 11 };
for (int i = 0; i < primeNumbers.Length; i++)
{
    Console.WriteLine($"Prime number at index {i}: {primeNumbers[i]}");
}

In this example, the for loop iterates through an array of prime numbers, printing each number along with its index.

Looping Through a List

List<double> temperatures = new List<double> { 68.5, 72.0, 75.5, 70.0 };
foreach (double temp in temperatures)
{
    Console.WriteLine($"Current temperature: {temp}°F");
}

Using the foreach loop, we can easily print each temperature recorded in the list.

Using LINQ for More Complex Queries

C# also offers Language Integrated Query (LINQ), which provides a more powerful way to work with collections. With LINQ, you can perform operations such as filtering, ordering, and transforming data with ease.

Example of using LINQ to filter a list:

List<int> ages = new List<int> { 18, 21, 17, 30, 25 };
var adults = ages.Where(age => age >= 18);

foreach (var adult in adults)
{
    Console.WriteLine($"Adult age: {adult}");
}

In this example, LINQ is used to filter the ages list, returning only those that represent adults.

When to Use Different Loop Types with Collections

Choosing the right loop type for your collection iteration can greatly impact the readability and performance of your code. Here are guidelines for when to use each loop:

  • For Loop: Best used when the number of iterations is known and when you need to access elements by index. It is also useful when you need to modify the collection during the iteration.
  • Foreach Loop: Ideal for iterating through collections when you do not need to modify the collection. It enhances code readability and reduces the likelihood of errors associated with index management.
  • While Loop: Suitable for scenarios where the number of iterations is uncertain. Use it when you need to repeat a block of code until a specific condition is met.
  • Do-While Loop: Use this loop when you need to ensure that the code block executes at least once, such as in user input scenarios.

Summary

Looping through collections in C# is a vital skill for intermediate and professional developers. By understanding the various loop types—for, foreach, while, and do-while—you can effectively iterate through different types of collections such as arrays and lists. Utilizing these loops appropriately enhances code readability, maintainability, and performance. As you become more familiar with these constructs, you’ll find that your ability to manipulate data within collections will improve significantly, leading to more efficient and effective coding practices. For more information, consider visiting the official Microsoft Documentation to deepen your understanding of loops in C#.

Last Update: 11 Jan, 2025

Topics:
C#
C#