Advertisement
JakeJBlues

Extension Method for building an Enumerator out of a .....

May 17th, 2012
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. // Implemention idea based on the following article
  2. // http://codingcraftsman.wordpress.com/2012/05/15/going-round-and-round/
  3.  
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8.  
  9. namespace IterateUntilNull {
  10.  
  11.    //The "generic logic" for an iterator which returns null at the end of a "list"
  12.    public class EnumeratorUntilNull<TIterator, TResult> where TIterator : class
  13.    {
  14.       public IEnumerable<TResult> Enumerator(TIterator iterator, Func<TIterator, TResult> func)
  15.       {
  16.          TResult next;
  17.          do
  18.          {
  19.             next = func(iterator);
  20.             if (next != null)
  21.             {
  22.                yield return next;
  23.             }
  24.          } while (next != null);
  25.       }
  26.    }
  27.  
  28.    // This is the base class for my finger exercise -> Random numbers a multiple of 1000 -> END
  29.    public class IterateUntilNull {
  30.       private Random r = new Random();
  31.  
  32.       public string GetNext() {
  33.          int checkNumber = r.Next(10000);
  34.          return (checkNumber%1000 == 0) ? null : checkNumber.ToString();
  35.       }
  36.    }
  37.  
  38.    // static extension method to inject the "Enumerator" into the base class
  39.    public static class IterateUntilNullExtensions {
  40.       public static IEnumerable<string> Enumerator(this IterateUntilNull iterator ) {
  41.          return new EnumeratorUntilNull<IterateUntilNull, string>().Enumerator(iterator, (i) => i.GetNext());
  42.       }
  43.    }
  44.  
  45.    
  46.    class Program {
  47.      
  48.       private static void Main(string[] args) {
  49.          // The calling
  50.          IterateUntilNull iun = new IterateUntilNull();
  51.          foreach(var item in iun.Enumerator() ) {
  52.             System.Console.WriteLine(item);
  53.          }
  54.          System.Console.ReadLine();
  55.       }
  56.    }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement