0

I have a for loop structured in the following way:

//MAIN CLASS
for (List<My_Data__c> myData : [soql_query]) {
    code_block
}

Can I pull the soql query out of the loop, place it in another class and refrence it as follows?

//ANOTHER CLASS
 public List<My_Data__c> getSoqlQuery() {
     return  [soql_query]                       
 }

//MAIN CLASS
 OtherClass otherClass = new OtherClass();

 for (My_Data__c myData : otherClass.getSoqlQuery()) {

        for (My_Data__c md : myData) { //ERROR OCCURS HERE
            //more stuff
        }
}

At the moment, I'm getting the following error when I try this:

Save error: Loop must iterate over a collection type SOBJECT:CCDEV18__My_Data__c

Can anyone see wht I'm doing wrong here?

2 Answers 2

2

for loop is capable of iterating through a list. So it's no matter it's from same class or from somewhere else. Just need to have a valid List to iterate.
The problem you are having is you are not accessing the list items correctly. Your query result is returning a List<My_data__c> where an item of it's My_Data__c. Alter your code into,

for (My_Data__c myData : otherClass.getSoqlQuery()) {
    code_block
}

I wonder if it was working when you had the list in the same class.

2
  • Cheers hihghfive! That fixed my issue alright, but another has popped up. I've a nested for statement inside my first for statement, now that one is blowing out. Ive updated my question above. Can you see what the problem is??
    – Daft
    Commented Jul 17, 2014 at 10:37
  • Why a second for loop? As already answered, query result is typeof List<My_Data__c> where you can iterate through it. In side that for loop you are having just a My_Data__c object and you can't iterate through an object.
    – highfive
    Commented Jul 17, 2014 at 10:51
1

List variable should be of type object not type of List. So please try to replace the below code as:

for (My_Data__c myData : otherClass.getSoqlQuery()){
  //do your stuff
}

rest of the code is fine.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .