Advertisement
Caminhoneiro

IENumerable<T> with Yield examples

Jun 21st, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.54 KB | None | 0 0
  1. //IENumerable and yield examples:
  2. //1:
  3.  
  4. public class PowersOf2
  5. {
  6.     static void Main()
  7.     {
  8.         // Display powers of 2 up to the exponent of 8:
  9.         foreach (int i in Power(2, 8))
  10.         {
  11.             Console.Write("{0} ", i);
  12.         }
  13.     }
  14.  
  15.     public static System.Collections.Generic.IEnumerable<int> Power(int number, int exponent)
  16.     {
  17.         int result = 1;
  18.  
  19.         for (int i = 0; i < exponent; i++)
  20.         {
  21.             result = result * number;
  22.             yield return result;
  23.         }
  24.     }
  25.  
  26.     // Output: 2 4 8 16 32 64 128 256
  27. }
  28.  
  29.  
  30.  
  31.  
  32. //Example 2:
  33. public static class GalaxyClass
  34. {
  35.     public static void ShowGalaxies()
  36.     {
  37.         var theGalaxies = new Galaxies();
  38.         foreach (Galaxy theGalaxy in theGalaxies.NextGalaxy)
  39.         {
  40.             Debug.WriteLine(theGalaxy.Name + " " + theGalaxy.MegaLightYears.ToString());
  41.         }
  42.     }
  43.  
  44.     public class Galaxies
  45.     {
  46.  
  47.         public System.Collections.Generic.IEnumerable<Galaxy> NextGalaxy
  48.         {
  49.             get
  50.             {
  51.                 yield return new Galaxy { Name = "Tadpole", MegaLightYears = 400 };
  52.                 yield return new Galaxy { Name = "Pinwheel", MegaLightYears = 25 };
  53.                 yield return new Galaxy { Name = "Milky Way", MegaLightYears = 0 };
  54.                 yield return new Galaxy { Name = "Andromeda", MegaLightYears = 3 };
  55.             }
  56.         }
  57.  
  58.     }
  59.  
  60.     public class Galaxy
  61.     {
  62.         public String Name { get; set; }
  63.         public int MegaLightYears { get; set; }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement