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=>...)
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:
That being said, this is a bad idea. LINQ queries should not have side effects if you can avoid it. Think of
Selectas a way to transform your data, not execute code.You could write your own extension method:
However, I would recommend not doing this. For details, refer to Eric Lippert’s post on the subject.