vulcan raven
vulcan raven

Reputation: 33562

IEnumerable with Yield statement

Consider the following code:

public static IEnumerable<float> Power(string ticker, float equity, float amount)
{
    for (int k = 0; MajicNumber(ref k, amount); )
    {
        yield return CalculateStats(ticker, equity, k);
        // Can we get the value of current resultset here?
    }
}

Since the function is maintaining the result-set, can we access it?

The traditional counterpart would be:

public static IEnumerable<float> Power(string ticker, float equity, float amount)
{
    List<float> resultSet = new List<float>();
    for (int k = 0; MajicNumber(ref k, amount); )
    {
        resultSet.Add(CalculateStats(ticker, equity, k));
        // resultSet is accessible here
    }
    return resultSet;
}

Upvotes: 2

Views: 180

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273179

Since the function is maintaining the result-set, can we access it?

No, an iterator block is not maintaining any resultset.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Sure, you can do that. The logic does not change much from the second code snippet, except that you yield return the answers as you find them:

public static IEnumerable<float> Power(string ticker, float equity, float amount)
{
    IList<float> resultSet = new List<float>();
    for (int k = 0; MajicNumber(ref k, amount); )
    {
        float r = CalculateStats(ticker, equity, k);
        resultSet.Add(r);
        yield return r;
    }
}

Upvotes: 3

Related Questions