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.         }

1 comment:

  1. شركة خطوه
    عجينه الصراصير
    تسمى عجينه الصراصيرباسم عجينة الحمض البوريك, وإليكم بعض الأشياء والأواني التي سوف نحتاجها في عمل تلك العجينة:
    • كوب من الماء الفاتر.
    • علبة بلاستيك تكون قديمة وغير مستعملة.
    • لبن بودرة.
    • حمض البوريك وهو ما يسمى البوريك أسيد.
    • مقدار من السكر.
    • مقدار من الدقيق.
    • قفاز من البلاستيك لليدين لعجن العجينة بأمان.
    • ملعقة من البلاستيك للتخلص منها بعد خلط العجينة.
    وعند خلط هذه المقادير لابد أن تكون جميعها متساوية مع بعضها البعض
    جميع خدمات شركة خطوة
    ترميم فلل
    صيانة فلل
    مكافحة حشرات
    http://www.khatwh.com

    ReplyDelete