First, I know there are methods off of the generic List<>
class already in the framework do iterate over the List<>
.
But as an example, what is the correct syntax to write a ForEach method to iterate over each object of a List<>
, and do a Console.WriteLine(object.ToString())
on each object.
Something that takes the List<>
as the first argument and the lambda expression as the second argument.
Most of the examples I have seen are done as extension methods or involve LINQ. I'm looking for a plain-old method example.
public void Each<T>(IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
action(item);
}
... and call it thusly:
Each(myList, i => Console.WriteLine(i));
The above could also be written with less code as:
new List<SomeType>(items).ForEach(
i => Console.WriteLine(i)
);
This creates a generic list and populates it with the IEnumerable and then calls the list objects ForEach.