views:

60

answers:

3

I'm writing a lazy list to retrieve items from a database with a given criteria and a given paging (start index and number of items desired).

At the instantiation of the list I count the total number of items in the mapped table, so that I have an initial size of the list (initial, because the list permits the addition and removal of items).

It almost works, but I'm having some troubles when determining the concrete number of items to fetch: in fact, i let users to specify a given fetch size (let's say 10, in this example).

To determine the exact number of items to fetch, at the present moment, I add the fetch size factor to the current index of the items in the collection (the last one retrieved from the database table): if the result is smaller or equal than the total count, I don't make any action (and the fetch works crystal clear), but if it is bigger of the total, my calculation of the remaining items to fetch fails.

Actually, to calculate the remaining items count, I subtract from the total count of items in the collection, the current index + 1 (the index is zero-based), which doesn't work in all conditions.

Have you got an idea on how to compute the right factors? Thank you a lot folks!

A: 

I believe you should do something like:

items_to_fetch = min( current_index + fetch_size, total_count )
Seb
A: 

How about:

items_to_fetch = max(0, min(fetch_size, total_count - current_index + 1))

Also make sure you get the current total count at the time of execution, not some cached value.

Galghamon
A: 

Thank you for the answers, but I found the solution, which wasn't so obvious nor so simple:

index -> destination index (within the collection)
diff_to_index -> index - current_index
items_to_fetch -> (current_index + 1) + items_to_fetch >= total_count ? total_count - (current_index + 1) : max(diff_to_index, fetch_size)

Cheers! :)

Antonello