LINQ ForEach
By Corneliu Dinca
We can use for a List<T> instance the equivalent of foreach. There are at least two reasons why List<T>.ForEach will be better:
1. Multi-Threading, possible by PLINQ;
2. Exceptions, you may want to collect all exception in the loop and throw it at once.
First example(inline implementation, using lambda-expressions):
System.Collections.ArrayList array = new System.Collections.ArrayList { 1, 2, 3, 4 };
IEnumerable<int> evenNumbers = array.Cast<int>().Where(r => r % 2 == 0);
evenNumbers.ToList().ForEach
(
(i)
=>
{
Console.Write(i+" ");
}
);
Second example(inline implementation, using delegate keyword):
System.Collections.ArrayList array = new System.Collections.ArrayList { 1, 2, 3, 4 };
IEnumerable<int> evenNumbers = array.Cast<int>().Where(r => r % 2 == 0);
evenNumbers.ToList().ForEach
(
delegate(int i)
{
Console.Write(i+" ");
}
);
Third
example:
public Example()
{
System.Collections.ArrayList array = new System.Collections.ArrayList { 1, 2, 3, 4 };
IEnumerable<int> evenNumbers = array.Cast<int>().Where(r => r % 2 == 0);
evenNumbers.ToList().ForEach(MyMethod);
}
private void MyMethod(int i)
{
Console.Write(i + " ");
}
Related FAQs
The Cast(IEnumerable) method enables the standard query operators to be invoked on non-generic collections. For example, if we want to query an ArrayList, we have to cast it first to IEnumerable
LINQ ForEach (7178 Views)