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
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#.
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.
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.
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.
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.
How to iterate with foreach loop in C#:
foreach
loop in C# simplifies iteration over collections, making it easier to traverse elements without the complexities of index management.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); } } }
C# foreach loop examples:
foreach
loop is versatile and can be used with various types of collections.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); } } }
C# foreach loop vs. for loop:
for
loops provide more control over iteration, foreach
loops are simpler for iterating over collections.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]); } } }
C# foreach loop dictionary:
foreach
to access key-value pairs.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"); } } }
Using foreach with IEnumerable in C#:
IEnumerable
can also be iterated with foreach
.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); } } }
C# foreach loop and break statement:
foreach
loop can be terminated prematurely using the break
statement.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; } } }
Foreach loop and LINQ in C#:
foreach
loops for expressive data manipulation.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); } } }
C# foreach loop index:
foreach
doesn't provide direct access to the index, you can use the Select
method with Enumerable.Range
to simulate an index.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}"); } } }
C# foreach loop with custom objects:
foreach
can be used with custom objects if the collection implements IEnumerable
or IEnumerable<T>
.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); } } }