Skip to main content
edited tags
Link
Chris Duncombe
  • 24.3k
  • 13
  • 77
  • 116
Source Link
ZAR
  • 2k
  • 5
  • 25
  • 41

List.add( value || 'default value')?

After querying for Account sObjects, I'm adding all the fields into a List. The problem is that some Account sObjects have certain fields and others do not. While adding the fields to my list, I'd like to be able to add field if it exists OR add a default string.

Let's go through the example.

My query:

List<Account> accountQuery = [SELECT name, (SELECT name, id FROM Contacts) FROM Account];

My map:

Map<String, List<String>> Result = new Map<String, List<String>>();

Iterating through the queryResult and saving the values:

For(Account i : accountQuery){
    String[] temp = new list<string>();
    temp.add(i.name)
    //Now loop through contacts subquery
    if(!i.contacts.isEmpty()){
        for(contact j : i.Contacts){
            temp.add(j.name || 'No Contact Name Associated'); //Doesn't work
            temp.add(j.id || 'No Contact Id Associated');
        }
    }
    else{
        temp.add('No Contact Name Associated');
        temp.add('No Contact Id Associated');
    }
};

How can I achieve this temp.add(value || 'default value')?

Thank you!