Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach with Extension Method on IEnumerable

Quick Question, See this code:

List<int> result = new List<int>();

var list = new List<int> { 1, 2, 3, 4 };

list.Select(value =>
    {
        result.Add(value);//Does not work??
        return value;
    });

And :

result.Count == 0 //true

Why result.Add(value) not executed?

However this not executed, Another question that is have a way do a foreach on a IEnumerable with Extention Method?

Except this way: IEnumerable.ToList().Foreach(p=>...)

like image 816
Reza ArabQaeni Avatar asked Dec 08 '11 21:12

Reza ArabQaeni


2 Answers

Why result.Add(value) not executed?

This is because LINQ uses deferred execution. Until you actually enumerate the results (the return of Select), the delegates will not execute.

To demonstrate, try the following:

List<int> result = new List<int>();

var list = new List<int> { 1, 2, 3, 4 };

var results = list.Select(value =>
    {
        result.Add(value);//Does not work??
        return value;
    });

foreach(var item in results)
{
     // Just iterating through this will cause the above to execute...
}

That being said, this is a bad idea. LINQ queries should not have side effects if you can avoid it. Think of Select as a way to transform your data, not execute code.

However this not executed, Another question that is have a way do a foreach on a IEnumerable with Extention Method?

You could write your own extension method:

public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
    foreach(var item in items)
         action(item);
}

However, I would recommend not doing this. For details, refer to Eric Lippert's post on the subject.

like image 91
Reed Copsey Avatar answered Oct 16 '22 10:10

Reed Copsey


Select is lazy and the execution is deferred until you start enumerating over the results. You need to consume the resultset by calling .ToArray for example or by looping over the result:

list.Select(value =>
    {
        result.Add(value);//Does not work??
        return value;
    }).ToArray();
like image 45
Darin Dimitrov Avatar answered Oct 16 '22 10:10

Darin Dimitrov