+ Start a Discussion
Carter85Carter85 

Help iterating through a wrapper class list and removing items based on criteria.

I have a list encapsulated in a wrapper class and I'm trying to remove items based on user defined criteria, it this case, whether or not it has been checked off on the list.  I can't seem to find the correct syntax for processing however, I always and up with an Illegal assignment error.
My current structure is:
Integer selectedCount2 = 0;
    	for(integer i = 0; i < tContractList.size(); i++){
    	if(!tContractList[i].selected){
            tContractList = tContractList.remove(i);
            }
        if(tContractList[i].selected == true){
        	selectedCount2++;
            }
			}
The error i get is: Compilation error: Illegal assignment from CM_RemittanceClass.contractWrapper to LIST&lt;CM_RemittanceClass.contractWrapper&gt;

Basically I just want to remove any item which hasn't been selected, so if anyone has a suggestion on the easiest way to do that I would appreciate it.
 
Best Answer chosen by Carter85
KevinPKevinP
Essentially, you can't delete from a list while iterating over it. So break this into two steps:
 
Integer selectedCount2 = 0;
List<Integer> toDelete = new List<Integer>();
for(integer i = 0; i < tContractList.size(); i++){
	if(!tContractList[i].selected){
		//first add it to the list to delete:
		toDelete.add(i);
	} else {
		selectedCount2++;		
	}
}
// remove it from your list.
for(Integer x : toDelete){
	tContractList.remove(x);
}

 

All Answers

KevinPKevinP
Essentially, you can't delete from a list while iterating over it. So break this into two steps:
 
Integer selectedCount2 = 0;
List<Integer> toDelete = new List<Integer>();
for(integer i = 0; i < tContractList.size(); i++){
	if(!tContractList[i].selected){
		//first add it to the list to delete:
		toDelete.add(i);
	} else {
		selectedCount2++;		
	}
}
// remove it from your list.
for(Integer x : toDelete){
	tContractList.remove(x);
}

 
This was selected as the best answer
Carter85Carter85
That fixed it, thanks.