IEnumerable Select

Can someone explain why the next C # line doesn't behave the same as the next foeach block?

string [] strs = {"asdf", "asd2", "asdf2"};
strs.Select(str => doSomething(str));


foreach(string str in strs){
  doSomething(str);
}

I set a breakpoint inside doSomething () and it does not fire in Select, but it does with foreach.

TIA

+5
source share
4 answers

The request Linqwill not be processed until you convert it to Enumarablewith ToList(), ToArray()etc.

And by the way, the equivalent of your operator foreachlooks something like this:

strs.ForEach (doSomething);

Strike>

strs.ToList().ForEach(doSomething);

or

Array.ForEach(strs, doSomething);
+1
source

, LINQ . , Select, .

Try:

string [] strs = {"asdf", "asd2", "asdf2"};
var result = strs.Select(str => doSomething(str));

foreach(var item in result) {
}
+10

you need to do something like

string [] strs = {"asdf", "asd2", "asdf2"};
strs = strs.Select(str => doSomething(str)).ToArray();


foreach(string str in strs){
  doSomething(str);
}
+1
source

I think that after using the values ​​returned from the selection, you will see doSomething () called. Check yield to see why this is happening.

0
source

All Articles