dharga
dharga

Reputation: 2217

IEnumerable Select

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

Answers (4)

fardjad
fardjad

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

Gent
Gent

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

SquidScareMe
SquidScareMe

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

Jakub Konecki
Jakub Konecki

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

Related Questions