Loops in Salesforce

Loops in Salesforce 

For Loops:-

  1. Apex supports three variations of the for loop

The Traditional for loop

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

-------- }

 

  1. 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.

 Interested in Salesforce? Check out this training to learn more on Salesforce training and Certification.

  1. 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 are associated with Contact Names.

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

This SOQL query will retrieves 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);

}

For Indepth understanding of Saleforce click on