fubo
fubo

Reputation: 45947

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?

Upvotes: 5

Views: 1086

Answers (2)

user310988
user310988

Reputation:

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>.

Upvotes: 9

xanatos
xanatos

Reputation: 111860

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>.

Upvotes: 7

Related Questions