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!
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(); } }
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; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With