C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# Foreach Loop Usage

In C#, the foreach loop is a powerful control structure that allows you to iterate over a collection or array without the need for an index variable. It provides a clean and elegant way to process each element in a collection. In this tutorial, we'll cover the basics of using foreach loops in C#.

  • Using foreach loop with arrays:

Here's an example of using a foreach loop to iterate over an array of integers:

int[] numbers = { 1, 2, 3, 4, 5 };

foreach (int number in numbers)
{
    Console.WriteLine(number);
}

The foreach loop iterates through each element in the numbers array, assigning the current element to the number variable.

  • Using foreach loop with lists:

You can also use the foreach loop with collections like List<T>. Here's an example using a List<string>:

using System;
using System.Collections.Generic;

List<string> names = new List<string>() { "Alice", "Bob", "Charlie" };

foreach (string name in names)
{
    Console.WriteLine(name);
}

In this example, the foreach loop iterates through each element in the names list, assigning the current element to the name variable.

  • Using foreach loop with dictionaries:

The foreach loop can also be used with dictionaries. When iterating over a dictionary, you can access the key-value pairs using the KeyValuePair<TKey, TValue> structure. Here's an example using a Dictionary<string, int>:

using System;
using System.Collections.Generic;

Dictionary<string, int> ages = new Dictionary<string, int>()
{
    { "Alice", 30 },
    { "Bob", 25 },
    { "Charlie", 28 }
};

foreach (KeyValuePair<string, int> kvp in ages)
{
    Console.WriteLine($"{kvp.Key} is {kvp.Value} years old.");
}

In this example, the foreach loop iterates through each key-value pair in the ages dictionary, assigning the current key-value pair to the kvp variable.

  • Using foreach loop with custom collections:

If you have a custom collection class, you can implement the IEnumerable or IEnumerable<T> interface and use the yield return statement to enable iteration with a foreach loop. Here's an example:

using System;
using System.Collections;
using System.Collections.Generic;

class MyNumbers : IEnumerable<int>
{
    public IEnumerator<int> GetEnumerator()
    {
        yield return 1;
        yield return 2;
        yield return 3;
        yield return 4;
        yield return 5;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyNumbers numbers = new MyNumbers();

        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

In this tutorial, we've covered the basics of using foreach loops in C#. The foreach loop provides a clean and elegant way to iterate over arrays, lists, dictionaries, and other collections, allowing you to process each element without the need for an index variable.

  1. How to iterate with foreach loop in C#:

    • Description: The foreach loop in C# simplifies iteration over collections, making it easier to traverse elements without the complexities of index management.
    • Code:
      using System;
      using System.Collections.Generic;
      
      class Program
      {
          static void Main()
          {
              // Example with an array
              int[] numbers = { 1, 2, 3, 4, 5 };
      
              // Iterate using foreach
              foreach (int number in numbers)
              {
                  Console.WriteLine(number);
              }
          }
      }
      
  2. C# foreach loop examples:

    • Description: The foreach loop is versatile and can be used with various types of collections.
    • Code:
      using System;
      using System.Collections.Generic;
      
      class Program
      {
          static void Main()
          {
              // Example with a list
              List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };
      
              // Iterate using foreach
              foreach (string fruit in fruits)
              {
                  Console.WriteLine(fruit);
              }
          }
      }
      
  3. C# foreach loop vs. for loop:

    • Description: While for loops provide more control over iteration, foreach loops are simpler for iterating over collections.
    • Code:
      using System;
      
      class Program
      {
          static void Main()
          {
              // Example with for loop
              int[] numbers = { 1, 2, 3, 4, 5 };
      
              for (int i = 0; i < numbers.Length; i++)
              {
                  Console.WriteLine(numbers[i]);
              }
          }
      }
      
  4. C# foreach loop dictionary:

    • Description: Dictionaries in C# can be iterated using foreach to access key-value pairs.
    • Code:
      using System;
      using System.Collections.Generic;
      
      class Program
      {
          static void Main()
          {
              // Example with a dictionary
              Dictionary<string, int> ages = new Dictionary<string, int>
              {
                  { "John", 25 },
                  { "Jane", 30 },
                  { "Bob", 22 }
              };
      
              // Iterate using foreach
              foreach (var pair in ages)
              {
                  Console.WriteLine($"{pair.Key}: {pair.Value} years old");
              }
          }
      }
      
  5. Using foreach with IEnumerable in C#:

    • Description: Custom collections implementing IEnumerable can also be iterated with foreach.
    • Code:
      using System;
      using System.Collections;
      
      class CustomCollection : IEnumerable
      {
          private int[] numbers = { 1, 2, 3, 4, 5 };
      
          // Implement IEnumerable.GetEnumerator
          IEnumerator IEnumerable.GetEnumerator()
          {
              return numbers.GetEnumerator();
          }
      }
      
      class Program
      {
          static void Main()
          {
              CustomCollection collection = new CustomCollection();
      
              // Iterate using foreach
              foreach (int number in collection)
              {
                  Console.WriteLine(number);
              }
          }
      }
      
  6. C# foreach loop and break statement:

    • Description: The foreach loop can be terminated prematurely using the break statement.
    • Code:
      using System;
      
      class Program
      {
          static void Main()
          {
              int[] numbers = { 1, 2, 3, 4, 5 };
      
              // Iterate using foreach with break
              foreach (int number in numbers)
              {
                  Console.WriteLine(number);
      
                  // Break the loop when a condition is met
                  if (number == 3)
                      break;
              }
          }
      }
      
  7. Foreach loop and LINQ in C#:

    • Description: LINQ queries can be seamlessly integrated with foreach loops for expressive data manipulation.
    • Code:
      using System;
      using System.Linq;
      using System.Collections.Generic;
      
      class Program
      {
          static void Main()
          {
              List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
      
              // LINQ query
              var evenNumbers = from num in numbers where num % 2 == 0 select num;
      
              // Iterate over the result using foreach
              foreach (int evenNumber in evenNumbers)
              {
                  Console.WriteLine(evenNumber);
              }
          }
      }
      
  8. C# foreach loop index:

    • Description: While foreach doesn't provide direct access to the index, you can use the Select method with Enumerable.Range to simulate an index.
    • Code:
      using System;
      using System.Linq;
      
      class Program
      {
          static void Main()
          {
              int[] numbers = { 10, 20, 30, 40, 50 };
      
              // Iterate with index using Select and Enumerable.Range
              foreach (var pair in Enumerable.Range(0, numbers.Length).Select(i => new { Index = i, Value = numbers[i] }))
              {
                  Console.WriteLine($"Index: {pair.Index}, Value: {pair.Value}");
              }
          }
      }
      
  9. C# foreach loop with custom objects:

    • Description: foreach can be used with custom objects if the collection implements IEnumerable or IEnumerable<T>.
    • Code:
      using System;
      using System.Collections;
      using System.Collections.Generic;
      
      class CustomObjectCollection : IEnumerable<int>
      {
          private List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
      
          // Implement IEnumerable.GetEnumerator
          IEnumerator IEnumerable.GetEnumerator()
          {
              return GetEnumerator();
          }
      
          // Implement IEnumerable<int>.GetEnumerator
          public IEnumerator<int> GetEnumerator()
          {
              return numbers.GetEnumerator();
          }
      }
      
      class Program
      {
          static void Main()
          {
              CustomObjectCollection customCollection = new CustomObjectCollection();
      
              // Iterate using foreach
              foreach (int number in customCollection)
              {
                  Console.WriteLine(number);
              }
          }
      }