0

Lets say we have a list with 156 items and we need to have them in 50 batches with take and skip methods, I have done below code but don't know how to skip previous items and if the rest of code is correct:

var mailAccounts = mailRepo.GetAllMailAccounts();
            int total = mailAccounts.Count;
            int batch = 50;
            int batchNumbers = total / batch;
            for (int i = 0; i < batchNumbers; i++)
            {
                mailAccounts.Skip(Previous Items).Take(batch);
                await FetchEmails(mailAccounts);
            }
Ehsan Davoudi
  • 185
  • 1
  • 4
  • 11
  • take an account that skip method doesn't use index offset when underlying type is array, and always enumerate underlying items... which can have performance inpact – Arsen Mkrtchyan Jan 29 '14 at 17:12

3 Answers3

5

You can easily calculate them:

int itemsToSkip = batch * i;
mailAccounts.Skip(itemsToSkip).Take(batch);
Andrei
  • 55,890
  • 9
  • 87
  • 108
  • BTW, skip method doesn't take an account the type of underlying collection, and enumerate collection on each call.. so the performance will be O(n^2), actually it can be done in O(n) with loop – Arsen Mkrtchyan Jan 29 '14 at 17:08
  • @ArsenMkrt, thanks for the comment, did not know that. However I won't object if the OP would sacrifice performance for code simplicity here, having only 156 objects – Andrei Jan 29 '14 at 17:21
  • that's true, for 156 objects the difference will not be visible... – Arsen Mkrtchyan Jan 29 '14 at 17:24
4
for (int i = 0; i < batchNumbers; i++) {
     mailAccounts.Skip(i * batch).Take(batch);
}
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
  • BTW, skip method doesn't take an account the type of underlying collection, and enumerate collection on each call.. so the performance of this method will be O(n^2), when it can be done on O(n) – Arsen Mkrtchyan Jan 29 '14 at 17:09
0
var chunks =  mailAccount.Select((m, i) => new {m, i})
                         .GroupBy(item = item.i / 50)
                         .Select(g => g.Select(item => item.m));

foreach(var ch in chunks)
{
   var curChunk = ch.ToArray();
}
Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184