Get the first 100 records in a list

Say i got a list

list<account> mylist = [select name from account];

what is the best way to get first 100 records in this list.

I mean convert mylist to mylist with first 100 records

Answer

You could have queried the list that way originally:

account[] mylist = [select id,name from account limit 100];

Or, you could copy them one at a time:

account[] mylist2 = new account[0];
integer counter = 0;
while(counter<100 && counter<mylist.size()) {
    mylist2.add(mylist[counter++]);
}

Update To find out if there are more records than can be displayed at once, set your limit one higher, and check for the presence of the max value:

account[] mylist = [select id,name from account limit 101];
if(mylist.size()==101) {
    mylist.remove(101);
    apexpages.addmessage(new apexpages.message(apexpages.severity.info,'More than 100 results found. Please narrow your search criteria.'));
}

Attribution
Source : Link , Question Author : sfdc99999 , Answer Author : sfdcfox

Leave a Comment