function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Priyesh Misquith 12Priyesh Misquith 12 

Querying over map

Hi,

I have a following map
map<String , Fruits__c> mapFruits = new map<String , Fruits__c>();
where Key is name of the fruit and  value is detail regarding fruit like color , taste etc.

Now i want to query on a different object called Tree__c based on key and values of this map mapFruits
List <tree__c> trees = [select region, name of the trees where fruitName = Should be the Key of the map and fruitTaste = field taste from the values of map and fruitColour ='field color from the values of map']

I am trying to avoid query inside the for loop.
Abhishek BansalAbhishek Bansal
Hi Priyesh,

You can use the below code snippet:
map<String , Fruits__c> mapFruits = new map<String , Fruits__c>();
//once this map is populated execute the below statemnets:

Set<String> setOfFruitsTaste = new Set<String>();
Set<String> setOfFruitsColor = new Set<String>();

for(Fruits__c fruit : mapFruits.values()) {
	//Replace Taste__c with API name of taste field on Fruit object
	if(fruit.Taste__c != null) {
		setOfFruitsTaste.add(fruit.Taste__c);
	}
	//Replace Color__c with API name of taste field on Fruit object
	if(fruit.Color__c != null) {
		setOfFruitsColor.add(fruit.Color__c);
	}
}

//Now you can query on Tree object like this:
List <tree__c> trees = [select region, name of the trees where fruitName IN :mapFruits.keySet() AND fruitTaste IN: setOfFruitsTaste AND fruitColour IN :setOfFruitsColor];

Please take care of the syntax errors and api name of the fields.

Thanks,
Abhishek Bansal.