elena1234

How to write your own Iterators

Feb 24th, 2021 (edited)
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.70 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3.  
  4. namespace IteratorsAndComparators
  5. {
  6.    public class Library : IEnumerable<Book> // IEnumerable<> NB!
  7.     {
  8.         public Library(params Book[] books)
  9.         {
  10.             this.Books = new List<Book>(books);
  11.         }
  12.  
  13.         public List<Book> Books { get; }
  14.  
  15.         public IEnumerator<Book> GetEnumerator()
  16.         {
  17.             return new LibraryEnumerator(this.Books); // this one automatically implementet constructor bellow
  18.         }
  19.  
  20.         IEnumerator IEnumerable.GetEnumerator()
  21.         {
  22.             return this.GetEnumerator(); // always return this.GetEnumerator()
  23.         }
  24.  
  25.         private class LibraryEnumerator : IEnumerator<Book> // IEnumerator<> NB!
  26.         {
  27.             private readonly List<Book> books;
  28.             private int currentIndex = -1; // add currentIndex
  29.  
  30.             public LibraryEnumerator(List<Book> books) // automatically implemented constructor
  31.             {
  32.                 this.Reset(); // add Reset()
  33.                 this.books = books;            
  34.             }
  35.             public Book Current => this.books[currentIndex];
  36.  
  37.             object IEnumerator.Current => this.Current; // always return this.Current
  38.  
  39.             public void Dispose()
  40.             {
  41.                
  42.             }
  43.  
  44.             public bool MoveNext()
  45.             {
  46.                this.currentIndex++;
  47.                 if (this.currentIndex >= this.books.Count)
  48.                 {
  49.                     return false;
  50.                 }
  51.  
  52.                 return true;
  53.             }
  54.  
  55.             public void Reset()
  56.             {
  57.                 this.currentIndex = -1;
  58.             }
  59.         }
  60.     }
  61. }
Add Comment
Please, Sign In to add comment