For a 20-point loop, skip each time
I would like to write a piece of a for loop that will loop through an existing list and display 20 elements from that list every time it iterates.
So something like this:
- If filterList contains, say, 68 elements ...
- The first 3 loops will take 20 times each, and then the last 4th iteration will leave the remaining 8 items that are in the list ...
I wrote something like this:
var allResponses= new List<string>();
for (int i = 0; i < filteredList.Count(); i++)
{
allResponses.Add(GetResponse(filteredList.Take(20).ToList()));
}
If filterList is supposed to be a list with 68 elements. I figured this is not the way to go because I don't want to loop over the size of the collections, but instead of 68 times it should be 4 times and every time I take 20 items from the list ... How can I do this?
source to share
You're pretty close - just add a call Skip
and divide Count
by 20, rounded up:
var allResponses= new List<string>();
for (int i = 0; i < (filteredList.Count+19) / 20; i++) {
allResponses.Add(GetResponse(filteredList.Skip(i*20).Take(20).ToList()));
}
The "add 19, divide by 20" trick provides an idiomatic way to take the "ceiling" of integer division rather than the "floor".
Edit: Better yet (thanks to Thomas Ayoub )
var allResponses= new List<string>();
for (int i = 0 ; i < filteredList.Count ; i = i + 20) {
allResponses.Add(GetResponse(filteredList.Skip(i).Take(20).ToList()));
}
source to share
You just need to calculate the number of pages:
const in PAGE_SIZE = 20;
int pages = filteredList.Count() / PAGE_SIZE
+ (filteredList.Count() % PAGE_SIZE > 0 ? 1 : 0)
;
The latter part ensures that at 21, 1 page is added above the previously calculated page size (starting at 21/20 = 1).
Or, using MoreLINQ, you can just use the call Batch
.
source to share
I offer a simple loop with page
the addition of 0
, 20
, 40
... iterations without Linq and complex modular operations:
int pageSize = 20;
List<String> page = null;
for (int i = 0; i < filteredList.Count; ++i) {
// if page reach pageSize, add a new one
if (i % pageSize == 0) {
page = new List<String>(pageSize);
allResponses.Add(page);
}
page.Add(filteredList[i]);
}
source to share