Foreach with extension method for 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 is result.Add (value) not executing?

However, this is not done. Another question that has a way to make foreach on IEnumerable with the Extention Method ?

Besides: IEnumerable.ToList().Foreach(p=>...)

+5
source share
3 answers

Why is result.Add (value) not executing?

This is because LINQ uses delayed execution. Until you list the results (return Select), delegates will not be executed.

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...
}

, . LINQ , . Select , .

. , foreach IEnumerable ?

:

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

. . .

+17

, , . , , , "ToArray" :

list.Select(value =>
    {
        result.Add(value);//Does not work??
        return value;
    }).ToArray();
+3
List<int> result = new List<int>();
var list = new List<int> { 1, 2, 3, 4 };
list.ForEach(delegate(int sValue)
{
    result.Add(sValue);
});

, 1 2 3 4 . . .

-1

All Articles