Looping over a list of sObjects that has more than object type

2018-06-14 19:13:12

I'm trying to access a field from a list of sObjects which holds 3 different objects types.

List data = new List();

for (sObject li : data) {

String sObjName = li.Id.getSObjectType().getDescribe().getName();

system.debug(sObjName);

if(String.valueOf(sObjName) == 'CR_Contract__c'){

Month = li.End_Date__c.month(); //Cannot access End_Date__c field

MonthN = String.valueOf(month);

}

}

How can I access the field to run logic?

There's a better way: the switch statement. You can now do this:

for(sObject li : data){

switch on li {

when CR_Contract__c cr {

Month = cr.End_Date__c.month();

...

}

when ... {

// etc

}

}

}

This new switch statement will help avoid typos as well, because they will be caught at compile-time.

I think I got it. I need to convert it to the type of sObject it is before I can access it.

if(String.valueOf(sObjName) == 'CR_Contract__c'){

CR_Contract_

  • There's a better way: the switch statement. You can now do this:

    for(sObject li : data){

    switch on li {

    when CR_Contract__c cr {

    Month = cr.End_Date__c.month();

    ...

    }

    when ... {

    // etc

    }

    }

    }

    This new switch statement will help avoid typos as well, because they will be caught at compile-time.

    2018-06-14 20:03:57
  • I think I got it. I need to convert it to the type of sObject it is before I can access it.

    if(String.valueOf(sObjName) == 'CR_Contract__c'){

    CR_Contract__c con = (CR_Contract__c)li;

    Month = con.End_Date__c.month();

    MonthN = String.valueOf(month);

    }

    2018-06-14 20:49:27