Apex For Loop

For Loops:

Apex supports three variations of the for loop

The Traditional for loop

for (i=0; i<=100; i++) {

-------- }

 

The list or set of iteration for loop`

for (variable ; List-or-set) {

}

Ex:

List <account > a = {select name from account};

for (Account acc: a)

{

------- Code block

}

Where variable (acc) must be of the same primitive or SObject n-type as List -or-set.

Inclined to build a profession as SalesForce Developer? Then here is the blog post on, explore SalesForce Training

The SOQL for loop:

for (variable: [Soql-query])

{ or variable list.

----

}

Both variable and variable-list must be of the same SObject type as is returned by the Soql-query.

EX:

for (Account a: [Select Name FROM Account where id='XXXXXXXXXX']

{

-------

}

(OR)

for( List <account> acc: [Select Name From account])

{

--------

Example for For Salesforce Loop SOQL Query

The following program displays the Account Names by one by one that is associated with Contact Names.

List <Contact > Lc = [Select Account Id, FirstName, LastName, account.accountid];

This SOQL query will retrieve the all the Contact records with Account Id, FirstName and LastName and Last Name filed values.

List > string > accid = new List <string> ();

For (contact c : lc)

{

accid. add (c. account id);

This statement adds all accountids to the acc id Variable.

System.debug ('The lists of IDs are ' + accid).

List < Account > la = [Select Name from Account where id =: acc

id];

for (Account Acc : la)

{

System.debug (Acc.Name);

}

 

Salesforce Tutorials

 

For In-depth understanding of Salesforce click on