0

I would like to exclude rows where Delta__c == Null. This can be done in 2 ways

1) only display odd rows using for loop 2) exlude rows where Delta__c == null

I am not sure how to modify list x after the For Loop. Can the same list be modified twice in APEX?

public with Sharing class EngagementDeltaController {



 public static Engagement__c[] getDelta() {

Engagement__c[] x = [SELECT Name, ID,Engagement_Score__c,CreatedDate,Account_ID__c,Delta__c FROM Engagement__c ORDER BY Account_ID__c,CreatedDate ASC];
if(!x.isEmpty()){
for(Integer i=1; i<x.size();i++)
{
    if(x[i].Account_ID__c == x[i-1].Account_ID__c)
    {
         x[i].Delta__c = x[i-1].Engagement_Score__c-x[i].Engagement_Score__c;        
      i++;
    }
    else system.debug('nothing found');
    }
   }
    return x;

 }
 }
  • 2
    You can modify a list e.g. use the remove method (or the add method) - take a look at the list documentation. But the code might be better written filtering before or during your existing loop. – Keith C Aug 25 '16 at 15:08
  • Perfect! x.remove(i-1); Worked – Mike Aug 25 '16 at 15:15
1

You could add a secondary list that stores the filtered results and return that instead of the original modified list.

public with Sharing class EngagementDeltaController {
  public static List<Engagement__c> getDelta() {
    List<Engagement__c> x = [SELECT Name, ID, Engagement_Score__c, CreatedDate, Account_ID__c, Delta__c FROM Engagement__c ORDER BY Account_ID__c, CreatedDate ASC];
    List<Engagement__c> filtered = new List<Engagement__c>();
    if(!x.isEmpty()){
      for(Integer i=1; i<x.size();i++) {
        if(x[i].Account_ID__c == x[i-1].Account_ID__c) {
          x[i].Delta__c = x[i-1].Engagement_Score__c-x[i].Engagement_Score__c; 
          if(x[i].Delta__c != null){
            filtered.add(x);
          }       
          i++;
        }
        else system.debug('nothing found');
      }
    }
    return filtered;
  }
}
  • That works. Thank you. Follow up question out of curosity: would it be possible to further filter the 'filtered' list e.g. display only the Top 10 records with highest Delta__c values? – Mike Aug 26 '16 at 14:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.