Monday, February 25, 2013

Working with bunch of items in small chunks using yield

Sometimes, we found ourselves in situations we we have to deal with large bunch of items and the code we are dealing with is unable to work with single large list. We then break large list into small chunks and process these chunks one by one. I found myself in such situations couple of times recently. So I decided to write some code which is efficient and is reusable.

Yield is a very useful keyword when worked with a collections. I used this to write an  extension method which takes a collection  and size of subset, split the collection into even sized small subsets and then return each subset one by one.

Here is my code,

  1. public static IEnumerable<IEnumerable<T>>
  2.         Subset<T>(this IEnumerable<T> list, int size)
  3.         {
  4.             int subset = 0;
  5.             do
  6.             {
  7.                 yield return list
  8.                     .Skip((subset++)*size)
  9.                     .Take(size);
  10.             } while (subset * size < list.Count());
  11.         }

2 comments: