Skip to main content
Zachariah Rosenberg ha preguntado en #Apex
Hello,

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!
6 respuestas
  1. 12 feb 2015, 18:42

    I think what you are looking for is more so the following:

    temp.add((String.isEmpty(j.name) ? 'No Contact Name Associated' : j.name));

    The above snippet uses a ternary operator that returns 'No Contact Name Associated' if Name is blank, otherwise the contact's name.  The output of the ternary is then added to the temp collection.
0/9000