How to use lambda expressions to iterate through an array in C#?
In C#, lambda expressions can be used to iterate through arrays. Here is an example:
int[] numbers = { 1, 2, 3, 4, 5 };
// 使用lambda表达式遍历数组
Array.ForEach(numbers, number => Console.WriteLine(number));
In the above code, we created an integer array called numbers. We then used the Array.ForEach method and a lambda expression to iterate through the array and print the value of each element. The lambda expression “number => Console.WriteLine(number)” represents performing the operation Console.WriteLine(number) on each element in the array.
The output result is:
1
2
3
4
5
In addition to using the Array.ForEach method, you can also use a foreach loop combined with a lambda expression to iterate through an array. An example is shown below:
int[] numbers = { 1, 2, 3, 4, 5 };
// 使用foreach循环和lambda表达式遍历数组
foreach (int number in numbers)
{
Console.WriteLine(number);
}
The output remains the same.