Reputation: 2217
Can someone explain why the following line of C# doesn't behave the same as the following foeach block?
string [] strs = {"asdf", "asd2", "asdf2"};
strs.Select(str => doSomething(str));
foreach(string str in strs){
doSomething(str);
}
I put a breakpoint inside of doSomething() and it doesn't fire in the Select but it does with the foreach.
TIA
Upvotes: 6
Views: 14119
Reputation: 20394
The Linq
query won't be processed until you convert it to an Enumarable
using ToList()
, ToArray()
, etc.
And by the way the equivalent to your foreach
statement is something like this:
strs.ForEach(doSomething);
strs.ToList().ForEach(doSomething);
or
Array.ForEach(strs, doSomething);
Upvotes: 1
Reputation: 2685
you would need to do something like
string [] strs = {"asdf", "asd2", "asdf2"};
strs = strs.Select(str => doSomething(str)).ToArray();
foreach(string str in strs){
doSomething(str);
}
Upvotes: 1
Reputation: 3218
I think once you use the values returned from the select you'll see doSomething() called. Check out yield to see why this is happening.
Upvotes: 0
Reputation: 46008
This is because LINQ queries are deferred. The lambda passed to the Select
method is actually executed when you access the result.
Try:
string [] strs = {"asdf", "asd2", "asdf2"};
var result = strs.Select(str => doSomething(str));
foreach(var item in result) {
}
Upvotes: 10