C# List – forEach
When you say for-each in the context of C# List, there are two different ways, namely forEach statement and ForEach() method.
forEach statement is a C# generic statement which you can use to iterate over elements of a List. Also, there is a ForEach() method that a List class implements in C#.
In this tutorial, we shall look into both of these, with examples.
Example 1 – C# List.ForEach()
List.ForEach() function accepts an Action and executes for each element in the list.
In the following program, we have a list with three numbers. We shall execute a delegate function, which gets the list element as argument, and executes the set of statements in its body, for the list element.
Please observe the type of parameter in the delegate function. nums
list contains elements of type int
. Therefore, the delegate function definition should contain the parameter of type int
.
Program.cs
using System;
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
//create list
List<int> nums = new List<int>();
//add elements to the list
nums.Add(56);
nums.Add(82);
nums.Add(94);
//list - foreach element
nums.ForEach(delegate(int num) {
Console.WriteLine(num);
});
}
}
Run the above C# program. The Action (delegate function) is executed for each element in the list. The body of the function is just a single statement to print the element to console.
Output
56
82
94
Example 2 – For Each Element in the List – forEach statement
In this example, we shall look into the forEach statement. The set of statements is executed for element in the list. You can access the element with the variable name you provide in the forEach definition. In this example, we have given the name num
.
Program.cs
using System;
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
//create list
List<int> nums = new List<int>();
nums.Add(52);
nums.Add(68);
nums.Add(73);
//for each element in the list
foreach (int num in nums) {
Console.WriteLine(num);
}
}
}
Run the above C# program.
Output
52
68
73
Example 3 – For Each Object in the List
In this example, we shall take a list of custom class objects. And execute ForEach() on this list of objects.
Program.cs
using System;
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
//create list
List<Car> cars = new List<Car>();
cars.Add(new Car("Toyota", 1250000));
cars.Add(new Car("Tata", 1300000));
cars.Add(new Car("Honda", 1150000));
//for each element in the list
cars.ForEach(delegate(Car car) {
Console.WriteLine(car.name + " - "+car.price);
});
}
}
class Car{
public string name;
public int price;
public Car(string name, int price){
this.name = name;
this.price = price;
}
}
Run the above C# program.
Output
Toyota - 1250000
Tata - 1300000
Honda - 1150000
Conclusion
In this C# Tutorial, we learned how to iterate through elements of C# List using forEach statement and List.ForEach().