yield return
-
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 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
-
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 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
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:
IEnumerable arr = Documented.GetValuesUpto(10);
MessageBox.Show(arr.ToList().Count.ToString());public static IEnumerable GetValuesUpto(int n)
{for (int ctr = 1; ctr <= n; ctr++) { yield return ctr; }
}
Put a breakpoint in the line
IEnumerable arr = Documented.GetValuesUpto(10);
. and also a breakpoint withinGetValueUpto
block. You will see the function is called when we try to callToList
() rather than the actual call toGetValueUpto
. This is the main advantage of iterator blocks. :rose::rose:Abhishek Sur
My Latest Articles **Create CLR objects in SQL Server 2005 C# Uncommon Keywords Read/Write Excel using OleDB
**Don't forget to click "Good Answer" if you like t