C# ForEach in LINQ

The ForEach method is not part of LINQ itself, but it can be used to iterate over a collection and execute an action on each element. Here's an example:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

numbers.ForEach(n => Console.WriteLine(n));

In this example, the ForEach method is used to iterate over the numbers list and print each element to the console.

To execute a foreach action under a Where condition in C#, you can use the Where method to filter the collection and then use foreach to iterate over the filtered elements. Here's an example:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

foreach (int n in numbers.Where(n => n % 2 == 0)) {
    Console.WriteLine(n);
}

In this example, the Where method is used to filter the numbers list to include only the even elements, and then the foreach loop is used to iterate over the filtered elements and print them to the console.

To execute multiple foreach actions under a Where condition in C#, you can use the same approach as above, but add multiple actions within the foreach loop. Here's an example:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
List<int> squares = new List<int>();

foreach (int n in numbers.Where(n => n % 2 == 0)) {
    Console.WriteLine(n);
    squares.Add(n * n);
}

foreach (int square in squares) {
    Console.WriteLine(square);
}

In this example, the Where method is used to filter the numbers list to include only the even elements, and then the foreach loop is used to iterate over the filtered elements, print them to the console, and compute and store their squares in the squares list. After the first loop, the second foreach loop is used to iterate over the squares list and print its elements to the console.

  1. Using ForEach with LINQ in C#:

    var numbers = Enumerable.Range(1, 5);
    numbers.ToList().ForEach(num => Console.WriteLine(num));
    
  2. C# LINQ query with ForEach:

    var numbers = Enumerable.Range(1, 5);
    var query = from num in numbers
                select num * 2;
    
    query.ToList().ForEach(result => Console.WriteLine(result));
    
  3. ForEach with condition in LINQ C#:

    var numbers = Enumerable.Range(1, 10);
    numbers.Where(num => num % 2 == 0).ToList().ForEach(evenNum => Console.WriteLine(evenNum));
    
  4. For Each and Where in LINQ C#:

    var numbers = Enumerable.Range(1, 10);
    numbers.Where(num => num % 2 == 0).ToList().ForEach(evenNum => Console.WriteLine(evenNum));
    
    • Use Where to filter elements before applying ForEach.