7

As a part of my first trigger, which is running on Opportunities, I have a list I created that contains the result of a SOQL query. Here is the code.

List<Custom_Object__c> mylist = [SELECT Id, Custom_Field_1__c FROM Custom_Object__c WHERE Custom_Field_2 = 'Value' AND Custom_Field__c > 0];

I have a custom field on Opportunities and I want to see if it's value matches a value of Custom_Field_1__c from this list. I've spent a fair amount of time looking around but am still stumped. How do I do this?

1 Answer 1

15

Instead of using a list you could put the values of Custom_Field_1__c into a set.

then when you do a compare you can use a method called contains.

set<string> myset = new set<string>(); 
For(Custom_Object__c m :mylist){ 
    myset.add(m.custom_field_1__c); 
} 

for (Opportunity o: Trigger.new) {
    myset.contains(o.Fieldvalue__c); //returns true/false
}
5
  • I need to convert the SOQL results, a list of sobjects, to set of strings (the value of Custom_Field_1__c). Can this be done?
    – dannymorty
    Commented Nov 8, 2012 at 22:39
  • 1
    You could iterate through your list of sobjects to populate the set. set<string> myset = new set<string>(); For(Custom_Object__c m :mylist){ myset.add(m.custom_field_1__c); } Then you can do MySet.contains('Comparison_String'); Commented Nov 9, 2012 at 2:39
  • 2
    Yo, Brian, I took the liberty of moving your code from the comment into the answer. I still don't have the rep to edit without peer review, so if someone wants to take a look, feel free to approve or reject. :-)
    – pchittum
    Commented Nov 9, 2012 at 10:14
  • This is exactly what I needed. Thank you so much to both of you!
    – dannymorty
    Commented Nov 9, 2012 at 14:42
  • Peter - well that was a good idea:) Thank you for moving it. Commented Nov 9, 2012 at 14:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .