Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: IEnumerable, GetEnumerator, a simple, simple example please!

Trying to create an uebersimple class that implements get enumerator, but failing madly due to lack of simple / non-functioning examples out there. All I want to do is create a wrapper around a data structure (in this case a list, but I might need a dictionary later) and add some functions.

public class Album {     public readonly string Artist;     public readonly string Title;     public Album(string artist, string title)     {          Artist = artist;          Title = title;     }  } public class AlbumList {     private List<Album> Albums = new List<Album>;     public Count { get { return Albums.Count; } }      .....     //Somehow GetEnumerator here to return Album } 

Thanks!

like image 328
Andrew White Avatar asked May 18 '10 19:05

Andrew White


2 Answers

You can simply return the enumerator returned by List<T>.GetEnumerator:

public class AlbumList : IEnumerable<Album> {     // ...      public IEnumerator<Album> GetEnumerator()     {         return this.albums.GetEnumerator();     }      IEnumerator IEnumerable.GetEnumerator()     {         return GetEnumerator();     } } 
like image 127
dtb Avatar answered Sep 24 '22 02:09

dtb


In addition to the other answers if you need a little more control over how the enumerator works or if there is a requirement to customize it beyond what the underlying data structure can provide then you can use the yield keyword.

public class AlbumList : IEnumerable<Album> {   public IEnumerator<Album> GetEnumerator()   {     foreach (Album item in internalStorage)     {       // You could use conditional checks or other statements here for a higher       // degree of control regarding what the enumerator returns.       yield return item;     }   } } 
like image 42
Brian Gideon Avatar answered Sep 24 '22 02:09

Brian Gideon