Foreach vs ForEach using crop

Is it possible to use yield built-in ForEach method?

 private static IEnumerable<string> DoStuff(string Input) { List<string> sResult = GetData(Input); sResult.ForEach(x => DoStuff(x)); //does not work sResult.ForEach(item => yield return item;); //does work foreach(string item in sResult) yield return item; } 

If not, is there a reason it doesn't work?

+5
source share
2 answers

Since, as you can see here , the lambda function is compiled according to a separate method:

It:

 x => DoStuff(x) 

converted to

 internal void <DoStuff>b__1_0(string x) { C.DoStuff(x); } 

This separate method is not IEnumerable<> , so it obviously cannot support the yield keyword.

So for example:

 item => yield return item; 

will be converted to:

 internal void <DoStuff>b__1_0(string item) { yield return item; } 

which has yield but not IEnumerable<string> .

+7
source

No, List<T>.ForEach cannot be used for this.

List<T>.ForEach accepts an Action<T> delegate.

Action<T> "Encapsulates a method that has a single parameter and does not return a value."

So, the lambda you created cannot return anything if it "fits" in Action<T> .

+9
source

Source: https://habr.com/ru/post/1244746/


All Articles