Infinite List of Database Users with Yield Return

At the ALT.NET Seattle conference, I went to a session by Nate Kohari on the awesomeness of the yield return keyword in .NET and how you can use it for all kinds of fancy stuff.

In the true spirit of over-engineering a solution, I have created this little property in one of my spec base classes:

   1: protected IEnumerable<User> DatabaseUserList
   2: {
   3:     get
   4:     {
   5:         while (true) yield return CreateUserInDatabase();
   6:     }
   7: }
   8:  
   9: protected User CreateUserInDatabase()
  10: {
  11:     var user = new UserBuilder().Build();
  12:     Repository<User>.Save(user);
  13:  
  14:     Flush();
  15:  
  16:     return user;
  17: }

We create what would be an infinite loop which creates Users over and over until the system runs out of memory, but since we’re using yield return, each user will only be created as we iterate over the list. Sexy.

Infinite data structures are a pretty common thing in functionaly programming languages with lazy evaluation. It wasn’t until this past weekend that I realized you could do the same thing in C#.

And using the delayed execution magic of yield return and our good friend LINQ, we can do things like:

   1: // Give me an IEnumerable<User> with 5 users in it.
   2: var users = DatabaseUserList.Take(5);
   3:  
   4: // Give me 1 user
   5: var user = DatabaseUserList.First();
   6:  
   7: // Force list creation, populates DB w/ 10 Users
   8: DatabaseUserList.Take(10).ToList();

So this will create users, stick them in the database, flush the database, all lazily as I iterate over a list of users. Is this a good idea? Probably not! But it’s hella cool.

This entry was posted in Development. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>