+ Start a Discussion
bouscalbouscal 

Loop through Cases, create List of Parent Cases?

I want to loop through a list of existing Cases and capture the Parent Case into another list.
What's the best way to accomplish this?  This code doesn't work because I'm trying to add an ID as an Object, so how do I add the sObject?
List<Case> childCases = new List<Case>([SELECT id, parentid FROM Case WHERE condition exists]);

List<Case> parentCases = new List<Case>();
for(Case c:childCases{
  parentCases.add(childCases.ParentId);
}

 
Best Answer chosen by bouscal
bouscalbouscal
my solution;
List<Case> childCases = new List<Case>([SELECT id, parentid FROM Case WHERE condition exists]);
Set<Id> parentIDs = new Set<Id>();

for(Case c:childCases{
   parentIDs.add(c.id);
}

List<Case> parentCases = new List<Case>([SELECT values FROM Case WHERE parentid IN:parentIDs]);

 

All Answers

TechnozChampTechnozChamp
List<Case> all_Cases=new list<Case>([Select id,parentid from case]);

List<id> Parent_Cases=new List<id>();

for (Case C:all_Cases)
{
Parent_cases.add(C.parentid);

}
bouscalbouscal
Thanks but I need a list of Cases, not a list of Ids.  I don't expect that I could use a list of IDs to update the Case objects associated with them without yet another List.
bouscalbouscal
my solution;
List<Case> childCases = new List<Case>([SELECT id, parentid FROM Case WHERE condition exists]);
Set<Id> parentIDs = new Set<Id>();

for(Case c:childCases{
   parentIDs.add(c.id);
}

List<Case> parentCases = new List<Case>([SELECT values FROM Case WHERE parentid IN:parentIDs]);

 
This was selected as the best answer