Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Implemention idea based on the following article
- // http://codingcraftsman.wordpress.com/2012/05/15/going-round-and-round/
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace IterateUntilNull {
- //The "generic logic" for an iterator which returns null at the end of a "list"
- public class EnumeratorUntilNull<TIterator, TResult> where TIterator : class
- {
- public IEnumerable<TResult> Enumerator(TIterator iterator, Func<TIterator, TResult> func)
- {
- TResult next;
- do
- {
- next = func(iterator);
- if (next != null)
- {
- yield return next;
- }
- } while (next != null);
- }
- }
- // This is the base class for my finger exercise -> Random numbers a multiple of 1000 -> END
- public class IterateUntilNull {
- private Random r = new Random();
- public string GetNext() {
- int checkNumber = r.Next(10000);
- return (checkNumber%1000 == 0) ? null : checkNumber.ToString();
- }
- }
- // static extension method to inject the "Enumerator" into the base class
- public static class IterateUntilNullExtensions {
- public static IEnumerable<string> Enumerator(this IterateUntilNull iterator ) {
- return new EnumeratorUntilNull<IterateUntilNull, string>().Enumerator(iterator, (i) => i.GetNext());
- }
- }
- class Program {
- private static void Main(string[] args) {
- // The calling
- IterateUntilNull iun = new IterateUntilNull();
- foreach(var item in iun.Enumerator() ) {
- System.Console.WriteLine(item);
- }
- System.Console.ReadLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement