I'm not able to get the sObject fields value in For loop.

Getting Loop must iterate over collection: SObject, Can you help me what I am missing here

sObject con = [SELECT Id, firstName, LastName FROM Contact];

for(sObject c : con){
id recid = (id)(c.getSObject('sObject').get('Name')); 
string name = String.valueOf(c.getSObject('sObject').get('firstName')); 
System.debug(recid + name);

1 Answer 1


You need to iterate over a list<Sobject> instead of sobject.

List<sObject> con = [SELECT Id, firstName, LastName FROM Contact];

You can learn how to loop through element from https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_loops.htm

  • +1, also the query is non-selective, so it would be better to have some condition with the WHERE clause. Aug 5, 2020 at 7:20

You must log in to answer this question.

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