Created
May 4, 2014 17:20
-
-
Save hervehobbes/a06a9638302284578014 to your computer and use it in GitHub Desktop.
Iterators & Yield in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace iterators | |
{ | |
public class Products | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
} | |
public class YieldInGet | |
{ | |
public IEnumerable<Products> GetProducts | |
{ | |
get | |
{ | |
yield return new Products() { Id = 1, Name = "Product1" }; | |
yield return new Products() { Id = 2, Name = "Product2" }; | |
yield return new Products() { Id = 3, Name = "Product3" }; | |
} | |
} | |
} | |
class Program | |
{ | |
public static IEnumerable<string> GetProducts() | |
{ | |
foreach (var item in Enumerable.Range(1, 5)) | |
{ | |
yield return "Product" + item.ToString(); | |
} | |
} | |
static void Main(string[] args) | |
{ | |
/* | |
foreach (var item in GetProducts()) | |
Console.WriteLine(item); | |
*/ | |
YieldInGet yg = new YieldInGet(); | |
foreach (Products p in yg.GetProducts) | |
Console.WriteLine(String.Format("Product Id: {0}, Name: {1}", p.Id, p.Name)); | |
foreach (var item in Fibonacci(5)) | |
{ | |
Console.WriteLine(item); | |
} | |
Console.WriteLine("Appuyez sur une touche"); | |
Console.ReadLine(); | |
} | |
public static IEnumerable<int> Fibonacci(int number) | |
{ | |
int a = 0, b = 1; | |
yield return a; | |
yield return b; | |
for (int count = 0; count <= number; count++) | |
{ | |
int temp = a; | |
a = b; | |
b = temp + b; | |
yield return b; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment