Click here to Skip to main content
15,881,173 members
Please Sign up or sign in to vote.
1.71/5 (3 votes)
See more: (untagged)
Hi,
I am using a enumerable function using "yield return". This allows me to iterate through the items using for each loop. Since this is a lazy evaluation, after each iteration the control returns to the calling function.

How can I use the enumerable function without for each loop?

public static IEnumerable<int> GetValuesUpto(int n)
{

for(int ctr = 1;ctr<=n;ctr++)
{
yield return ctr;
}
}

So, when I call this function i.e.
int[] arr = GetValuesUpto(10);

What would be the result, will it work like a lazy evaluation and will return only the first value, or will it return the desired result?

Waiting for your replies guys!!
Vishwjeet
Posted

1 solution

Iterator blocks are called when you want to fetch the data from the Enumerable.

Actually if you call the the function, it will not be called. Rather if you do a foreach on the Enumerable object the function will be called and will return you 10. ;-)

Just change your code a bit as I did:

<br />IEnumerable<int> arr = Documented.GetValuesUpto(10);<br />MessageBox.Show(arr.ToList<int>().Count.ToString());


public static IEnumerable<int> GetValuesUpto(int n)<br />{<br /><br />    for (int ctr = 1; ctr <= n; ctr++)<br />    {<br /><br />       yield return ctr;<br />    }<br />            <br />}


Put a breakpoint in the line IEnumerable<int> arr = Documented.GetValuesUpto(10);. and also a breakpoint within GetValueUpto block. You will see the function is called when we try to call ToList() rather than the actual call to GetValueUpto. This is the main advantage of iterator blocks.

[Rose][Rose]

 
Share this answer
 


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900