迭代列表并删除顶点中的重复项

时间:2016-08-17 14:30:43

标签: salesforce apex

我想根据列表中的“名称”字段删除重复的条目。 以下是我的代码..

 public class EPM_Contact_Component_Class {
     public List<Hospital_Contacts__c> conList { get; set; }
     public List<Hospital_Contacts__c> result { get; set; }
     public JCT_Hospital_Model__c jctObj { get; set; }
     public Set<Hospital_Contacts__c> myset { get; set; }

 public EPM_Contact_Component_Class(ApexPages.StandardController controller) { }

 public List<Hospital_Contacts__c> getContacts() {
     conList = new List<Hospital_Contacts__c>();
     jctObj = new JCT_Hospital_Model__c();
     jctObj = [Select EPM_Model__r.Name,Hospital__r.Name from JCT_Hospital_Model__c where Id=:ApexPages.currentPage().getParameters().get('Id')];
     system.debug(jctObj.EPM_Model__r.Name);
     conList = [select Contacts__r.Name,Contacts__r.Email,Contacts__r.Phone from Hospital_Contacts__c where EPM_Model__r.Name =: jctObj.EPM_Model__r.Name and Hospital__r.Name=:jctObj.Hospital__r.Name  ORDER BY Contacts__r.Name DESC ];

     myset = new Set<Hospital_Contacts__c>();
     result = new List<Hospital_Contacts__c>();

      for(integer i=0;i<conList.size();i++) {
             Hospital_Contacts__c hospi = conList.get(i);
         for(integer j=(i+1);j<conList.size();j++) {

             Hospital_Contacts__c hospj = conList.get(j); 
             if(hospi.Contacts__r.Name == hospj.Contacts__r.Name) {
                 conList.remove(j); 
                 system.debug('REMOVED::'+j);  
             }
         }
     }
     return conList;
 }

}

它可以正常使用2个重复项。当重复项超过2个时,它会返回2次名称。 有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:0)

我解决了这个问题。将Second For循环更改为

**for(j=i;j<conList.size();j++)**

答案 1 :(得分:0)

将内部for循环更改为:

for(integer j=0;j<conList.size();j++)

将您的if条件更改为:

if(hospi.Contacts__r.Name == hospj.Contacts__r.Name && i!=j)