C # - action on IEnumerable <T>
I implemented this extension method:
public static IEnumerable<T> DoForEach<T>(this IEnumerable<T> data, Action<T> action) { foreach (T value in data) { action(value); yield return value; } } when i do
output.DoForEach<string>(c => Console.WriteLine(c)); nothing is written to the console. Any ideas why this is not working? thanks
yield return makes the request lazy, in other words, your method is only executed when iterating over the elements starts. Many LINQ statements are executed if a deferred mode . The following code demonstrates this problem.
new[] {1,2}.DoForEach(Console.WriteLine).ToList(); prints:
1 2 while
new[] {1,2}.DoForEach(Console.WriteLine); doesn't print anything
for a complete example, check out the following snippet:
IEnumerable items = new[] {1,2}.DoForEach(s => Console.WriteLine("inside query:"+s)); foreach (var item in items) { Console.WriteLine ("inside loop:" + item); } it will print
inside query:1 inside loop:1 inside query:2 inside loop:2 and it will only start typing in the first iteration of foreach . When building a query, elements are not printed
This is because you are returning an iterator but not executing it. Given what you wrote, you want to perform some action on the list, rather than returning an enumerator to it, so it seems to you that the DoForEach () function returns void and gets rid of returning returns to This. This should be written to the console.
Edit: here is a snippet showing what I mean:
public static void DoForEach<T>(this IEnumerable<T> data, Action<T> action) { foreach (T value in data) { action(value); } }