The List<t>
class already has a method doing the same job as:
public static void ForEach<t>(this IList<t> list, Action<t> function)
More about the ForEach
method is available here. Here is the reflected ForEach
method:
public void ForEach(Action<T> action)
{
if (action == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
for (int i = 0; i < this._size; i++)
{
action(this._items[i]);
}
}
to show the inner implementation of .NET ForEach()
of List<t>
. So we can use this .NET built in ForEach
method to do the job, for example, if we want to process List<t>
elements, we can try:
List<string> myList = new List<string>() { "One", "Two" };
myList.ForEach(item => Console.WriteLine(item));
and with the Where
clause:
myList.Where(item => item == "One").ToList().ForEach(item => Console.WriteLine(item));
From the above code, we can see the Where
clause will return an IEnumerable<t>
object, so we cast it to List<t>
using ToList()
and then apply the ForEach
method over it.
And also over IList<t>
elements:
IList<string> myList = new List<string>() { "One", "Two" };
myList.ToList().ForEach(item => Console.WriteLine(item));
myList.Where(item => item == "One").ToList().ForEach(item => Console.WriteLine(item));