foreach vs ForEach using yield

Is it possible to use yield inline at the 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 why it doesn't work?

Answers


Because as you can see here a lambda function is compiled to a separate method:

This:

x => DoStuff(x)

is converted to

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

This separate method isn't a IEnumerable<> so it clearly can't support the yield keyword.

So for example this:

item => yield return item;

would be converted to:

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

that has the yield but isn't IEnumerable<string>.


No, List<T>.ForEach can't be used for this.

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

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

So the lambda you've created can't return anything if it's to "fit" in an Action<T>.


Need Your Help

What substring algorithm (to find a string) does PHP use?

php c algorithm substring

I have been trying to figure out what substring algorithm (to find a string in another string). PHP uses, I have found the following piece of code in the PHP source on GitHub: