Search code examples
c#entity-frameworklinqlinq-to-sqllinq-to-entities

How do I SKIP the already iterated rows but read the next rows that are not being iterated?


I am trying to loop through a collection i.e. but it should iterate only according to the pagination value.

See, I have this:

var SkipCount= 0;
var TakeCount= 50;

var list= db.tblCollection.where(r => r.Id > 1).orderby(r=> r.Id).Take(Take).Skip(SkipCount);

var totalTableRecords= list.count(); // 200 records in my case
var counter= 0;

now the outer loop shall be running until it reaches the total value of totalTableRecords-1. And for inner loop for each iteration of outer loop it shall check only take the specified number of records.

for( ;counter < totalTableRecords; )
{
     foreach(var l in list)
     {
          //Do some coding here
          
          counter= counter + 1;
          
     }
          SkipCount= TakeCount;
          TakeCount= TakeCount+ 50;
          
}
          

What I am trying to achieve is that in 1st run of outer loop the inner loop shall do some execution based on the trimmed i.e. 1st 50 records. Then, in the second run we do need to skip the already executed 50 records in 1st run and shall be the next 50 records. Then in the third loop it shall ignore the already read 100 records in 1st and 2nd run (50+50) and next 50 records until the counter of outer loop hits the condition.

I tried this but it keep on running till the limit i.e. 200 while the actual work is done is only 4 iterations.

How do I solve this?


Solution

  • I have a feeling the code you posted is not quite the same as what you've been testing. Changing SkipCount and TakeCount inside the inner loop (for every item you iterate through) seems wrong.

    I'll rewrite a bit, but overall: just keep TakeCount (page size) constant and increase SkipCount (page number):

    pageNum = 0; // Instead of SkipCount
    pageSize = 50; // Instead of TakeCount
    List<SomeType> page;
    
    do
    {
        page = db.tblCollection.Where(r => r.Id > 1)
            .OrderBy(r => r.Id)
            .Skip(pageNum * pageSize)
            .Take(pageSize)
            .ToList();
    
         foreach (var l in page)
         {
              //Do some coding here
         }
    
         pageNum++;
    } while (page.Count > 0);