+ Start a Discussion
SoCal AdminSoCal Admin 

FOR / Iteration problem of List<List<>>

Hi Everyone!

 

I'm a newbie to apex code and I'm tryng out a new user-based SOSL query in a visual force page. But  I don't understand the resulting LIST or how to iterate over it using a FOR statement.

 

I perform a SOSL query with the following:

List<List<Myobject>> searchList = [FIND '*00*' IN ALL FIELDS RETURNING Myobject];

 

it seems to work correctly based on the logs from the DeveloperConsole.

 

I get this data back (from DeveloperConsole System.Debug):

USER_DEBUG   [34][DEBUG] Items Found: 1

USER_DEBUG   [34][DEBUG] ITEM: (Myobject:{Id=01tE0000000MKAYIA4}, Myobject:Id=01tE0000000MKAUIA4}, Myobject:Id=01tE0000000MKASIA4}, Myobject:Id=01tE0000000MKATIA4}, Myobject:Id=01tE0000000MKANIA4}, Myobject:Id=01tE0000000MKAQIA4},...)

 

The output was doctored because I didn't spend time to find a text export of the logs,

 

But the SIZE property returns "1" as indicated in the logs and a FOR loop does not work as expected.  It seems I may have a Single List of a multi-valued List (as indicated in the code above).

 

How do I get this to work in FOR loop to iterate over the the returning values?

How can I bypass the List<List<myobject>> to replace it with List<MyObject>?

 

Why do I need to use the List<List<>> syntax at all?  It was the only way I could get it to return the list set.

 

Here is the For Loop:

 

for (List<MyObject> s1 : searchList) {
        System.Debug('Item: ' + s1);
        i++;
  }

 

 

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Andrew WilkinsonAndrew Wilkinson

SOSL always returns a List of lists. This is because it can traverse multiple objects. To return your list do this.

 

After you initialize your SOSL initialize a new list based on the results

 

 

List<MyObject> newList = (List<MyObject>)searchList[0];

 

then loop over the newList...

 

for (MyObject m : newList){

//logic

}

 

or you could put both in a for loop

 

for(MyObject m : (List<MyObject>)searchList[0]){

//logic

}

All Answers

Andrew WilkinsonAndrew Wilkinson

SOSL always returns a List of lists. This is because it can traverse multiple objects. To return your list do this.

 

After you initialize your SOSL initialize a new list based on the results

 

 

List<MyObject> newList = (List<MyObject>)searchList[0];

 

then loop over the newList...

 

for (MyObject m : newList){

//logic

}

 

or you could put both in a for loop

 

for(MyObject m : (List<MyObject>)searchList[0]){

//logic

}

This was selected as the best answer
SoCal AdminSoCal Admin

Andrew,

 

I didn't bother testing your suggestion when I read it because I kind of knew the answer - so I marked your response as the "Solution" as soon as you confirmed my suspicions.

 

Ii just tested it, and, as expected, you *rock*!!!